USB-Meter / USB Meter / Views / ChargedDevices / Details / ChargedDeviceSettingsView.swift
Newer Older
1092 lines | 43.119kb
Bogdan Timofte authored a month ago
1
//
2
//  ChargedDeviceSettingsView.swift
3
//  USB Meter
4
//
5
//  Created by Codex on 10/04/2026.
6
//
7

            
8
import SwiftUI
9

            
10
struct ChargedDeviceSettingsView: View {
11
    private enum DetailTab: Hashable {
12
        case overview
13
        case standby
14
        case sessions
15
        case trends
16
        case settings
17
    }
18

            
19
    @EnvironmentObject private var appData: AppData
20
    @Environment(\.dismiss) private var dismiss
21

            
22
    @State private var editorVisibility = false
23
    @State private var deleteConfirmationVisibility = false
24
    @State private var selectedTab: DetailTab = .overview
25
    @State private var sessionSelectMode = false
26
    @State private var selectedSessionIDs: Set<UUID> = []
27
    @State private var pendingBatchDeletion = false
28

            
29
    let chargedDeviceID: UUID
30

            
31
    var body: some View {
32
        Group {
33
            if let chargedDevice = appData.chargedDeviceSummary(id: chargedDeviceID) {
34
                tabbedDetailView(chargedDevice)
35
                .navigationTitle(chargedDevice.name)
36
                .navigationBarTitleDisplayMode(.inline)
37
            } else {
38
                Text("This device is no longer available.")
39
                    .foregroundColor(.secondary)
40
                    .navigationTitle("Device")
41
                    .navigationBarTitleDisplayMode(.inline)
42
            }
43
        }
44
        .sidebarToggleToolbarItem()
45
        .sheet(isPresented: $editorVisibility) {
46
            if let chargedDevice = appData.chargedDeviceSummary(id: chargedDeviceID) {
47
                if chargedDevice.isCharger {
48
                    ChargerEditorSheetView(chargedDevice: chargedDevice)
49
                        .environmentObject(appData)
50
                } else {
Bogdan Timofte authored a month ago
51
                    ChargedDeviceEditorSheetView(chargedDevice: chargedDevice)
Bogdan Timofte authored a month ago
52
                    .environmentObject(appData)
53
                }
54
            }
55
        }
56
        .confirmationDialog("Delete \(deletionTitle)?", isPresented: $deleteConfirmationVisibility, titleVisibility: .visible) {
57
            Button("Delete", role: .destructive) {
58
                if appData.deleteChargedDevice(id: chargedDeviceID) {
59
                    dismiss()
60
                }
61
            }
62
            Button("Cancel", role: .cancel) {}
63
        } message: {
64
            Text(deletionMessage)
65
        }
66
        .confirmationDialog(
67
            "Delete \(selectedSessionIDs.count) Session\(selectedSessionIDs.count == 1 ? "" : "s")?",
68
            isPresented: $pendingBatchDeletion,
69
            titleVisibility: .visible
70
        ) {
71
            Button("Delete", role: .destructive, action: deleteSelectedSessions)
72
            Button("Cancel", role: .cancel) {}
73
        } message: {
74
            Text("Deleting these sessions also recalculates capacity and every derived metric that used them.")
75
        }
76
    }
77

            
78
    private func tabbedDetailView(_ chargedDevice: ChargedDeviceSummary) -> some View {
79
        GeometryReader { proxy in
80
            let tabs = availableTabs(for: chargedDevice)
81
            let displayedTab = displayedTab(from: tabs)
82
            let tabBarPresentation = AdaptiveTabBarPresentation.standard(for: proxy.size)
83

            
84
            VStack(spacing: 0) {
85
                ChargedDeviceDetailTabBarView(
86
                    tabs: tabs,
87
                    selection: $selectedTab,
88
                    tint: tint(for: chargedDevice),
89
                    presentation: tabBarPresentation,
90
                    title: title(for:),
91
                    systemImage: systemImage(for:)
92
                )
93

            
94
                Group {
95
                    if displayedTab == .sessions {
96
                        sessionsTabLayout(chargedDevice)
97
                    } else {
98
                        ScrollView {
99
                            tabContent(displayedTab, chargedDevice: chargedDevice)
100
                                .padding()
101
                        }
102
                    }
103
                }
104
                .id(displayedTab)
105
                .transition(.opacity.combined(with: .move(edge: .trailing)))
106
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
107
            }
108
            .animation(.easeInOut(duration: 0.22), value: displayedTab)
109
            .animation(.easeInOut(duration: 0.22), value: tabs)
110
            .onChange(of: selectedTab) { _ in
111
                sessionSelectMode = false
112
                selectedSessionIDs.removeAll()
113
            }
114
        }
115
        .background(detailBackground(for: chargedDevice))
116
        .onAppear {
117
            ensureSelectedTabExists(for: chargedDevice)
118
        }
119
        .onChange(of: chargedDevice.isCharger) { _ in
120
            ensureSelectedTabExists(for: chargedDevice)
121
        }
122
    }
123

            
124
    @ViewBuilder
125
    private func tabContent(_ tab: DetailTab, chargedDevice: ChargedDeviceSummary) -> some View {
126
        VStack(spacing: 18) {
127
            switch tab {
128
            case .overview:
129
                overviewTab(chargedDevice)
130
            case .standby:
131
                standbyTab(chargedDevice)
132
            case .sessions:
133
                sessionsTab(chargedDevice)
134
            case .trends:
135
                trendsTab(chargedDevice)
136
            case .settings:
137
                settingsTab(chargedDevice)
138
            }
139
        }
140
    }
141

            
142
    @ViewBuilder
143
    private func overviewTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
144
        headerCard(chargedDevice)
145
        insightsCard(chargedDevice)
146

            
147
        if let activeSession = chargedDevice.activeSession {
148
            activeSessionSummaryCard(activeSession, chargedDevice: chargedDevice)
149
        }
150
    }
151

            
152
    @ViewBuilder
153
    private func standbyTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
154
        standbyPowerCard(chargedDevice)
155
    }
156

            
157
    @ViewBuilder
158
    private func sessionsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
159
        if let activeSession = chargedDevice.activeSession {
160
            activeSessionSummaryCard(activeSession, chargedDevice: chargedDevice)
161
        }
162

            
163
        let sessions = closedSessions(for: chargedDevice)
164
        if !sessions.isEmpty {
165
            sessionListCard(sessions, chargedDevice: chargedDevice)
166
        } else if chargedDevice.activeSession == nil {
167
            emptyStateCard(
168
                title: "No Sessions",
169
                message: "Charging sessions will appear here after this device is used in a recording.",
170
                tint: .teal
171
            )
172
        }
173
    }
174

            
175
    @ViewBuilder
176
    private func trendsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
177
        if !chargedDevice.capacityHistory.isEmpty {
178
            capacityEvolutionCard(chargedDevice)
179
        }
180

            
181
        if !chargedDevice.typicalCurve.isEmpty {
182
            typicalCurveCard(chargedDevice)
183
        }
184

            
185
        if chargedDevice.capacityHistory.isEmpty && chargedDevice.typicalCurve.isEmpty {
186
            emptyStateCard(
187
                title: "Learning Trends",
188
                message: "Capacity history and charge curves will appear after enough completed sessions are available.",
189
                tint: .blue
190
            )
191
        }
192
    }
193

            
194
    @ViewBuilder
195
    private func settingsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
196
        settingsCard(chargedDevice)
197
    }
198

            
199
    @ViewBuilder
200
    private func sessionsTabLayout(_ chargedDevice: ChargedDeviceSummary) -> some View {
201
        let allSessions = chargedDevice.sessions.sorted { lhs, rhs in
202
            let lOpen = lhs.status.isOpen, rOpen = rhs.status.isOpen
203
            if lOpen != rOpen { return lOpen }
204
            return lhs.startedAt > rhs.startedAt
205
        }
206
        let totalEnergyWh = allSessions.reduce(0.0) { $0 + $1.effectiveOrMeasuredEnergyWh }
207
        let totalDuration  = allSessions.reduce(0.0) { $0 + max($1.effectiveDuration, 0) }
208

            
209
        VStack(spacing: 0) {
210
            // Fixed non-scrolling header
211
            VStack(spacing: 10) {
212
                sessionsSummaryStrip(
213
                    count: allSessions.count,
214
                    totalEnergyWh: totalEnergyWh,
215
                    totalDuration: totalDuration,
216
                    hasActive: chargedDevice.activeSession != nil
217
                )
218

            
219
                if !allSessions.isEmpty {
220
                    HStack(spacing: 12) {
221
                        if sessionSelectMode && !selectedSessionIDs.isEmpty {
222
                            Text("\(selectedSessionIDs.count) selected")
223
                                .font(.subheadline)
224
                                .foregroundColor(.secondary)
225
                                .transition(.opacity.combined(with: .move(edge: .leading)))
226
                        }
227
                        Spacer()
228
                        if sessionSelectMode && !selectedSessionIDs.isEmpty {
229
                            Button {
230
                                pendingBatchDeletion = true
231
                            } label: {
232
                                Image(systemName: "trash").foregroundColor(.red)
233
                            }
234
                            .transition(.opacity.combined(with: .scale))
235
                        }
236
                        Button(sessionSelectMode ? "Cancel" : "Select") {
237
                            withAnimation(.easeInOut(duration: 0.2)) {
238
                                sessionSelectMode.toggle()
239
                                if !sessionSelectMode { selectedSessionIDs.removeAll() }
240
                            }
241
                        }
242
                    }
243
                    .animation(.easeInOut(duration: 0.2), value: sessionSelectMode)
244
                    .animation(.easeInOut(duration: 0.2), value: selectedSessionIDs.isEmpty)
245
                }
246
            }
247
            .padding()
248

            
249
            // Scrollable session list
250
            if allSessions.isEmpty {
251
                emptyStateCard(
252
                    title: "No Sessions",
253
                    message: "Charging sessions will appear here after this device is used in a recording.",
254
                    tint: .teal
255
                )
256
                .padding([.horizontal, .bottom])
257
            } else {
258
                ScrollView {
259
                    VStack(spacing: 10) {
260
                        ForEach(allSessions, id: \.id) { session in
261
                            sessionListItem(session, chargedDevice: chargedDevice)
262
                        }
263
                    }
264
                    .padding([.horizontal, .bottom])
265
                }
266
            }
267
        }
268
    }
269

            
270
    private func sessionsSummaryStrip(
271
        count: Int,
272
        totalEnergyWh: Double,
273
        totalDuration: TimeInterval,
274
        hasActive: Bool
275
    ) -> some View {
276
        HStack(spacing: 0) {
277
            summaryCell(value: "\(count)", label: count == 1 ? "session" : "sessions")
278
            Divider().frame(height: 30)
279
            summaryCell(value: "\(totalEnergyWh.format(decimalDigits: 2)) Wh", label: "energy")
280
            Divider().frame(height: 30)
281
            summaryCell(value: formatAccumulatedDuration(totalDuration), label: "duration")
282
            if hasActive {
283
                Divider().frame(height: 30)
284
                HStack(spacing: 4) {
285
                    Circle().fill(Color.green).frame(width: 6, height: 6)
286
                    Text("Live")
287
                        .font(.caption2.weight(.semibold))
288
                        .foregroundColor(.green)
289
                }
290
                .frame(maxWidth: .infinity)
291
            }
292
        }
293
        .padding(.vertical, 8)
294
        .padding(.horizontal, 12)
295
        .meterCard(tint: .teal, fillOpacity: 0.08, strokeOpacity: 0.14, cornerRadius: 14)
296
    }
297

            
298
    private func summaryCell(value: String, label: String) -> some View {
299
        VStack(spacing: 2) {
300
            Text(value)
301
                .font(.subheadline.weight(.bold))
302
                .foregroundColor(.primary)
303
                .monospacedDigit()
304
                .lineLimit(1)
305
                .minimumScaleFactor(0.7)
306
            Text(label)
307
                .font(.caption2)
308
                .foregroundColor(.secondary)
309
        }
310
        .frame(maxWidth: .infinity)
311
    }
312

            
313
    private func formatAccumulatedDuration(_ duration: TimeInterval) -> String {
314
        let formatter = DateComponentsFormatter()
315
        formatter.allowedUnits = duration >= 3600 ? [.hour, .minute] : [.minute, .second]
316
        formatter.unitsStyle = .abbreviated
317
        formatter.zeroFormattingBehavior = .dropAll
318
        return formatter.string(from: duration) ?? "0m"
319
    }
320

            
321
    private func headerCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
322
        HStack(alignment: .top, spacing: 18) {
323
            ChargedDeviceQRCodeView(qrIdentifier: chargedDevice.qrIdentifier, side: 118)
324

            
325
            VStack(alignment: .leading, spacing: 10) {
326
                ChargedDeviceIdentityLabelView(
327
                    chargedDevice: chargedDevice,
328
                    iconPointSize: 22
329
                )
330
                .font(.title3.weight(.bold))
331

            
332
                Text(chargedDevice.identityTitle)
333
                    .font(.subheadline.weight(.semibold))
334
                    .foregroundColor(.secondary)
335

            
336
                Text(chargedDevice.qrIdentifier)
337
                    .font(.caption2.monospaced())
338
                    .foregroundColor(.secondary)
339
                    .textSelection(.enabled)
340
            }
341

            
342
            Spacer(minLength: 0)
343
        }
344
        .frame(maxWidth: .infinity, alignment: .leading)
345
        .padding(18)
346
        .meterCard(tint: tint(for: chargedDevice), fillOpacity: 0.20, strokeOpacity: 0.26, cornerRadius: 20)
347
    }
348

            
349
    private func settingsCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
350
        MeterInfoCardView(title: "Settings", tint: tint(for: chargedDevice)) {
351
            MeterInfoRowView(
352
                label: "Kind",
353
                value: chargedDevice.isCharger ? "Charger" : chargedDevice.deviceClass.title
354
            )
355
            MeterInfoRowView(label: "Template", value: chargedDevice.identityTitle)
356
            MeterInfoRowView(label: "QR ID", value: chargedDevice.qrIdentifier)
357

            
358
            MeterInfoRowView(label: "Created", value: chargedDevice.createdAt.format())
359
            MeterInfoRowView(label: "Updated", value: chargedDevice.updatedAt.format())
360

            
361
            Divider()
362

            
363
            Button(action: showEditor) {
364
                Label("Edit \(chargedDevice.isCharger ? "Charger" : "Device")", systemImage: "pencil")
365
                    .font(.subheadline.weight(.semibold))
366
                    .frame(maxWidth: .infinity)
367
                    .padding(.vertical, 10)
368
                    .meterCard(tint: tint(for: chargedDevice), fillOpacity: 0.16, strokeOpacity: 0.22, cornerRadius: 14)
369
            }
370
            .buttonStyle(.plain)
371

            
372
            Button(role: .destructive, action: showDeleteConfirmation) {
373
                Label("Delete \(chargedDevice.isCharger ? "Charger" : "Device")", systemImage: "trash")
374
                    .font(.subheadline.weight(.semibold))
375
                    .frame(maxWidth: .infinity)
376
                    .padding(.vertical, 10)
377
                    .meterCard(tint: .red, fillOpacity: 0.10, strokeOpacity: 0.18, cornerRadius: 14)
378
            }
379
            .buttonStyle(.plain)
380
        }
381
    }
382

            
383
    private func emptyStateCard(title: String, message: String, tint: Color) -> some View {
384
        VStack(alignment: .leading, spacing: 8) {
385
            Text(title)
386
                .font(.headline)
387
            Text(message)
388
                .font(.footnote)
389
                .foregroundColor(.secondary)
390
                .fixedSize(horizontal: false, vertical: true)
391
        }
392
        .frame(maxWidth: .infinity, alignment: .leading)
393
        .padding(18)
394
        .meterCard(tint: tint, fillOpacity: 0.12, strokeOpacity: 0.18, cornerRadius: 18)
395
    }
396

            
397
    private func insightsCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
398
        MeterInfoCardView(title: "Insights", tint: tint(for: chargedDevice)) {
399
            if chargedDevice.isCharger {
400
                chargerInsights(chargedDevice)
401
            } else {
402
                deviceInsights(chargedDevice)
403
            }
404

            
405
            if let notes = chargedDevice.notes, !notes.isEmpty {
406
                Divider()
407
                Text(notes)
408
                    .font(.footnote)
409
                    .foregroundColor(.secondary)
410
                    .frame(maxWidth: .infinity, alignment: .leading)
411
            }
412
        }
413
    }
414

            
415
    @ViewBuilder
416
    private func deviceInsights(_ chargedDevice: ChargedDeviceSummary) -> some View {
417
        if chargedDevice.hasMultipleChargingStateModes {
418
            MeterInfoRowView(
419
                label: "Charge Modes",
420
                value: chargedDevice.chargingStateAvailability.title
421
            )
422
        }
423
        if chargedDevice.hasMultipleChargingTransports {
424
            MeterInfoRowView(
425
                label: "Charging Support",
426
                value: chargedDevice.supportedChargingModes.map(\.title).joined(separator: " + ")
427
            )
428
        }
429
        if chargedDevice.showsWirelessProfileDetails {
430
            MeterInfoRowView(
431
                label: "Wireless Profile",
432
                value: chargedDevice.wirelessChargingProfile.title
433
            )
434
        }
435

            
436
        ForEach(completionSessionKinds(for: chargedDevice), id: \.rawValue) { sessionKind in
437
            MeterInfoRowView(
438
                label: completionCurrentLabel(for: chargedDevice, sessionKind: sessionKind),
439
                value: completionCurrentDescription(for: chargedDevice, sessionKind: sessionKind)
440
            )
441
        }
442
        MeterInfoRowView(
443
            label: "Estimated Capacity",
444
            value: chargedDevice.estimatedBatteryCapacityWh.map { "\($0.format(decimalDigits: 2)) Wh" } ?? "Not enough data"
445
        )
446
        if let wiredCapacity = chargedDevice.wiredEstimatedBatteryCapacityWh {
447
            if chargedDevice.hasMultipleChargingTransports {
448
                MeterInfoRowView(
449
                    label: "Wired Capacity",
450
                    value: "\(wiredCapacity.format(decimalDigits: 2)) Wh"
451
                )
452
            }
453
        }
454
        if let wirelessCapacity = chargedDevice.wirelessEstimatedBatteryCapacityWh {
455
            if chargedDevice.hasMultipleChargingTransports {
456
                MeterInfoRowView(
457
                    label: "Wireless Capacity",
458
                    value: "\(wirelessCapacity.format(decimalDigits: 2)) Wh"
459
                )
460
            }
461
        }
462
        if let wirelessEfficiencyFactor = chargedDevice.wirelessChargerEfficiencyFactor,
463
           chargedDevice.showsWirelessProfileDetails {
464
            MeterInfoRowView(
465
                label: "Wireless Efficiency",
466
                value: "\(Int((wirelessEfficiencyFactor * 100).rounded()))%"
467
            )
468
        }
469
        MeterInfoRowView(
470
            label: "Charge Sessions",
471
            value: "\(chargedDevice.sessionCount)"
472
        )
473
    }
474

            
475
    @ViewBuilder
476
    private func chargerInsights(_ chargedDevice: ChargedDeviceSummary) -> some View {
477
        if let chargerType = chargedDevice.chargerType {
478
            MeterInfoRowView(
479
                label: "Type",
480
                value: chargerType.title
481
            )
482
        }
483
        if !chargedDevice.chargerObservedVoltageSelections.isEmpty {
484
            MeterInfoRowView(
485
                label: "Observed Voltages",
486
                value: chargedDevice.chargerObservedVoltageSelections
487
                    .map { "\($0.format(decimalDigits: 1)) V" }
488
                    .joined(separator: ", ")
489
            )
490
        }
491
        if let chargerIdleCurrentAmps = chargedDevice.chargerIdleCurrentAmps {
492
            MeterInfoRowView(
493
                label: "Idle Current",
494
                value: "\(chargerIdleCurrentAmps.format(decimalDigits: 2)) A"
495
            )
496
        }
497
        if let chargerEfficiencyFactor = chargedDevice.chargerEfficiencyFactor {
498
            MeterInfoRowView(
499
                label: "Efficiency",
500
                value: "\(Int((chargerEfficiencyFactor * 100).rounded()))%"
501
            )
502
        }
503
        if let chargerMaximumPowerWatts = chargedDevice.chargerMaximumPowerWatts {
504
            MeterInfoRowView(
505
                label: "Max Power",
506
                value: "\(chargerMaximumPowerWatts.format(decimalDigits: 2)) W"
507
            )
508
        }
509
        if let latestStandbyPowerMeasurement = chargedDevice.latestStandbyPowerMeasurement {
510
            MeterInfoRowView(
511
                label: "Standby Power",
512
                value: "\(latestStandbyPowerMeasurement.averagePowerWatts.format(decimalDigits: 3)) W"
513
            )
514
            MeterInfoRowView(
515
                label: "Standby Projection",
516
                value: standbyEnergyLabel(latestStandbyPowerMeasurement.projectedYearlyEnergyWh) + " / year"
517
            )
518
        }
519
        MeterInfoRowView(
520
            label: "Wireless Sessions",
521
            value: "\(chargedDevice.sessionCount)"
522
        )
523

            
524
    }
525

            
526
    private func standbyPowerCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
527
        let latestMeasurement = chargedDevice.latestStandbyPowerMeasurement
528

            
529
        return MeterInfoCardView(
530
            title: "Standby Power",
531
            tint: .orange
532
        ) {
533
            if standbyMeasurementMeters.isEmpty {
534
                Text("Connect a meter first. Standby measurement is launched from a live meter feed, so only currently available meters can be selected here.")
535
                    .font(.footnote)
536
                    .foregroundColor(.secondary)
537
                    .frame(maxWidth: .infinity, alignment: .leading)
538
            } else {
539
                NavigationLink(
540
                    destination: ChargerStandbyPowerWizardView(
541
                        preferredChargerID: chargedDevice.id,
542
                        locksChargerSelection: true
543
                    )
544
                ) {
545
                    Label("New Measurement", systemImage: "plus.circle.fill")
546
                        .font(.subheadline.weight(.semibold))
547
                        .foregroundColor(.orange)
548
                }
549
                .buttonStyle(.plain)
550
            }
551

            
552
            if let latestMeasurement {
553
                Divider()
554

            
555
                NavigationLink(
556
                    destination: ChargerStandbyPowerMeasurementDetailView(
557
                        chargerID: chargedDevice.id,
558
                        measurementID: latestMeasurement.id
559
                    )
560
                ) {
561
                    VStack(alignment: .leading, spacing: 8) {
562
                        HStack {
563
                            Text("Latest Measurement")
564
                                .font(.subheadline.weight(.semibold))
565
                                .foregroundColor(.primary)
566
                            Spacer()
567
                            Text("\(latestMeasurement.averagePowerWatts.format(decimalDigits: 3)) W")
568
                                .font(.subheadline.weight(.bold))
569
                                .foregroundColor(.primary)
570
                                .monospacedDigit()
571
                        }
572

            
573
                        Text(
574
                            "\(latestMeasurement.endedAt.format()) • \(latestMeasurement.sampleCount) samples • \(standbyEnergyLabel(latestMeasurement.projectedYearlyEnergyWh)) / year"
575
                        )
576
                        .font(.caption)
577
                        .foregroundColor(.secondary)
578
                    }
579
                }
580
                .buttonStyle(.plain)
581
            }
582

            
583
            if chargedDevice.standbyPowerMeasurements.isEmpty == false {
584
                Divider()
585

            
586
                NavigationLink(
587
                    destination: ChargerStandbyPowerMeasurementsView(chargerID: chargedDevice.id)
588
                ) {
589
                    Label("View Saved Measurements", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
590
                        .font(.subheadline.weight(.semibold))
591
                        .foregroundColor(.blue)
592
                }
593
                .buttonStyle(.plain)
594
            }
595
        }
596
    }
597

            
598
    private func activeSessionSummaryCard(
599
        _ activeSession: ChargeSessionSummary,
600
        chargedDevice: ChargedDeviceSummary
601
    ) -> some View {
602
        NavigationLink(
603
            destination: ChargeSessionDetailView(
604
                chargedDeviceID: chargedDevice.id,
605
                sessionID: activeSession.id
606
            )
607
        ) {
608
            VStack(alignment: .leading, spacing: 14) {
609
                HStack(alignment: .firstTextBaseline) {
610
                    VStack(alignment: .leading, spacing: 4) {
611
                        Text("Current Session")
612
                            .font(.headline)
613
                            .foregroundColor(.primary)
614
                        Text(activeSession.status.title)
615
                            .font(.caption.weight(.semibold))
616
                            .foregroundColor(statusTint(for: activeSession))
617
                    }
618

            
619
                    Spacer()
620

            
621
                    Image(systemName: "chevron.right")
622
                        .font(.caption.weight(.semibold))
623
                        .foregroundColor(.secondary)
624
                }
625

            
626
                LazyVGrid(columns: activeSessionSummaryColumns, spacing: 8) {
627
                    activeSessionMetricCell(
628
                        label: "Energy",
629
                        value: "\(activeSession.effectiveOrMeasuredEnergyWh.format(decimalDigits: 2)) Wh",
630
                        tint: .teal
631
                    )
632
                    activeSessionMetricCell(
633
                        label: "Duration",
634
                        value: sessionDurationText(activeSession),
635
                        tint: .orange
636
                    )
637
                    if let maximumObservedPowerWatts = activeSession.maximumObservedPowerWatts {
638
                        activeSessionMetricCell(
639
                            label: "Max Power",
640
                            value: "\(maximumObservedPowerWatts.format(decimalDigits: 2)) W",
641
                            tint: .blue
642
                        )
643
                    }
644
                    if let batteryPrediction = chargedDevice.batteryLevelPrediction(for: activeSession) {
645
                        activeSessionMetricCell(
646
                            label: "Battery",
647
                            value: "\(batteryPrediction.predictedPercent.format(decimalDigits: 0))%",
648
                            tint: .green
649
                        )
650
                    } else if let targetBatteryPercent = activeSession.targetBatteryPercent {
651
                        activeSessionMetricCell(
652
                            label: "Target",
653
                            value: "\(targetBatteryPercent.format(decimalDigits: 0))%",
654
                            tint: .indigo
655
                        )
656
                    }
657
                }
658

            
659
                Text("Started \(activeSession.startedAt.format())")
660
                    .font(.caption)
661
                    .foregroundColor(.secondary)
662
            }
663
        }
664
        .buttonStyle(.plain)
665
        .padding(18)
666
        .meterCard(tint: statusTint(for: activeSession), fillOpacity: 0.16, strokeOpacity: 0.22, cornerRadius: 18)
667
    }
668

            
669
    private var activeSessionSummaryColumns: [GridItem] {
670
        [
671
            GridItem(.flexible(minimum: 92), spacing: 8),
672
            GridItem(.flexible(minimum: 92), spacing: 8)
673
        ]
674
    }
675

            
676
    private func activeSessionMetricCell(label: String, value: String, tint: Color) -> some View {
677
        VStack(alignment: .leading, spacing: 4) {
678
            Text(label)
679
                .font(.caption2)
680
                .foregroundColor(.secondary)
681
            Text(value)
682
                .font(.footnote.weight(.semibold))
683
                .foregroundColor(.primary)
684
                .monospacedDigit()
685
                .lineLimit(1)
686
                .minimumScaleFactor(0.8)
687
        }
688
        .frame(maxWidth: .infinity, alignment: .leading)
689
        .padding(10)
690
        .meterCard(tint: tint, fillOpacity: 0.08, strokeOpacity: 0.12, cornerRadius: 12)
691
    }
692

            
693
    private func capacityEvolutionCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
694
        VStack(alignment: .leading, spacing: 12) {
695
            Text("Capacity Evolution")
696
                .font(.headline)
697

            
698
            ForEach(chargedDevice.capacityHistory.suffix(6)) { point in
699
                HStack {
700
                    Text(point.timestamp.format())
701
                        .font(.caption)
702
                        .foregroundColor(.secondary)
703
                    Spacer()
704
                    if chargedDevice.shouldShowChargingTransport(point.chargingTransportMode) {
705
                        Text(point.chargingTransportMode.title)
706
                            .font(.caption2)
707
                            .foregroundColor(.secondary)
708
                        Text("•")
709
                            .foregroundColor(.secondary)
710
                    }
711
                    Text("\(point.capacityWh.format(decimalDigits: 2)) Wh")
712
                        .font(.footnote.weight(.semibold))
713
                }
714
            }
715
        }
716
        .frame(maxWidth: .infinity, alignment: .leading)
717
        .padding(18)
718
        .meterCard(tint: .orange, fillOpacity: 0.14, strokeOpacity: 0.20, cornerRadius: 18)
719
    }
720

            
721
    private func typicalCurveCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
722
        VStack(alignment: .leading, spacing: 12) {
723
            Text("Typical Charge Curve")
724
                .font(.headline)
725

            
726
            ForEach(chargedDevice.typicalCurve) { point in
727
                HStack {
728
                    Text("\(point.percentBin)%")
729
                        .font(.footnote.weight(.semibold))
730
                    Spacer()
731
                    Text("\(point.averageEnergyWh.format(decimalDigits: 2)) Wh")
732
                        .font(.caption.weight(.semibold))
733
                    Text("•")
734
                        .foregroundColor(.secondary)
735
                    Text("\(point.sampleCount) sample\(point.sampleCount == 1 ? "" : "s")")
736
                        .font(.caption2)
737
                        .foregroundColor(.secondary)
738
                }
739
            }
740
        }
741
        .frame(maxWidth: .infinity, alignment: .leading)
742
        .padding(18)
743
        .meterCard(tint: .blue, fillOpacity: 0.14, strokeOpacity: 0.20, cornerRadius: 18)
744
    }
745

            
746
    private func sessionListCard(
747
        _ sessions: [ChargeSessionSummary],
748
        chargedDevice: ChargedDeviceSummary
749
    ) -> some View {
750
        let totalEnergyWh = sessions.reduce(0) { $0 + $1.effectiveOrMeasuredEnergyWh }
751
        let completedCount = sessions.filter { $0.status == .completed }.count
752
        let sortedSessions = sessions.sorted { $0.startedAt > $1.startedAt }
753

            
754
        return VStack(alignment: .leading, spacing: 14) {
755
            MeterInfoCardView(title: "Closed Sessions", tint: .teal) {
756
                MeterInfoRowView(label: "Sessions", value: "\(sessions.count)")
757
                MeterInfoRowView(label: "Completed", value: "\(completedCount)")
758
                MeterInfoRowView(label: "Total Energy", value: "\(totalEnergyWh.format(decimalDigits: 2)) Wh")
759
            }
760

            
761
            HStack(spacing: 12) {
762
                if sessionSelectMode && !selectedSessionIDs.isEmpty {
763
                    Text("\(selectedSessionIDs.count) selected")
764
                        .font(.subheadline)
765
                        .foregroundColor(.secondary)
766
                        .transition(.opacity.combined(with: .move(edge: .leading)))
767
                }
768
                Spacer()
769
                if sessionSelectMode && !selectedSessionIDs.isEmpty {
770
                    Button {
771
                        pendingBatchDeletion = true
772
                    } label: {
773
                        Image(systemName: "trash")
774
                            .foregroundColor(.red)
775
                    }
776
                    .transition(.opacity.combined(with: .scale))
777
                }
778
                Button(sessionSelectMode ? "Cancel" : "Select") {
779
                    withAnimation(.easeInOut(duration: 0.2)) {
780
                        sessionSelectMode.toggle()
781
                        if !sessionSelectMode { selectedSessionIDs.removeAll() }
782
                    }
783
                }
784
            }
785
            .animation(.easeInOut(duration: 0.2), value: sessionSelectMode)
786
            .animation(.easeInOut(duration: 0.2), value: selectedSessionIDs.isEmpty)
787

            
788
            VStack(spacing: 10) {
789
                ForEach(sortedSessions, id: \.id) { session in
790
                    sessionListItem(session, chargedDevice: chargedDevice)
791
                }
792
            }
793
        }
794
    }
795

            
796
    private func sessionListItem(
797
        _ session: ChargeSessionSummary,
798
        chargedDevice: ChargedDeviceSummary
799
    ) -> some View {
800
        let sessionTint = statusTint(for: session)
801
        let isOpen = session.status.isOpen
802
        let isSelected = selectedSessionIDs.contains(session.id)
803

            
804
        return Group {
805
            if sessionSelectMode && !isOpen {
806
                Button {
807
                    withAnimation(.easeInOut(duration: 0.15)) {
808
                        if isSelected { selectedSessionIDs.remove(session.id) }
809
                        else          { selectedSessionIDs.insert(session.id) }
810
                    }
811
                } label: {
812
                    sessionRowContent(session, sessionTint: sessionTint, isOpen: isOpen, isSelected: isSelected)
813
                }
814
                .buttonStyle(.plain)
815
            } else {
816
                NavigationLink(
817
                    destination: ChargeSessionDetailView(
818
                        chargedDeviceID: chargedDevice.id,
819
                        sessionID: session.id
820
                    )
821
                ) {
822
                    sessionRowContent(session, sessionTint: sessionTint, isOpen: isOpen, isSelected: false)
823
                }
824
                .buttonStyle(.plain)
825
            }
826
        }
827
    }
828

            
829
    private func sessionRowContent(
830
        _ session: ChargeSessionSummary,
831
        sessionTint: Color,
832
        isOpen: Bool,
833
        isSelected: Bool
834
    ) -> some View {
835
        VStack(alignment: .leading, spacing: 10) {
836
            HStack(alignment: .firstTextBaseline, spacing: 10) {
837
                if sessionSelectMode {
838
                    Group {
839
                        if isOpen {
840
                            Image(systemName: "minus.circle")
841
                                .foregroundColor(.secondary.opacity(0.35))
842
                        } else {
843
                            Image(systemName: isSelected ? "checkmark.circle.fill" : "circle")
844
                                .foregroundColor(isSelected ? .teal : .secondary)
845
                        }
846
                    }
847
                    .font(.body)
848
                    .transition(.opacity)
849
                }
850

            
851
                VStack(alignment: .leading, spacing: 2) {
852
                    Text(session.startedAt.format())
853
                        .font(.subheadline.weight(.semibold))
854
                    Text(session.status.title)
855
                        .font(.caption2)
856
                        .foregroundColor(sessionTint)
857
                }
858

            
859
                Spacer()
860

            
861
                VStack(alignment: .trailing, spacing: 2) {
862
                    Text("\(session.effectiveOrMeasuredEnergyWh.format(decimalDigits: 2)) Wh")
863
                        .font(.subheadline.weight(.semibold))
864
                        .foregroundColor(.primary)
865
                    Text(sessionDurationText(session))
866
                        .font(.caption)
867
                        .foregroundColor(.secondary)
868
                }
869
            }
870

            
871
            Divider()
872

            
873
            HStack(spacing: 8) {
874
                if let batteryDelta = session.batteryDeltaPercent {
875
                    Label("\(batteryDelta >= 0 ? "+" : "")\(Int(batteryDelta.rounded()))% charged", systemImage: "battery.100percent")
876
                        .font(.caption2)
877
                        .foregroundColor(.secondary)
878
                }
879

            
880
                if let capacityWh = session.capacityEstimateWh {
881
                    Text("est. \(capacityWh.format(decimalDigits: 1)) Wh")
882
                        .font(.caption2)
883
                        .foregroundColor(.secondary)
884
                }
885

            
886
                Spacer()
887

            
888
                if !session.displayedAggregatedSamples.isEmpty {
889
                    Label("\(session.displayedAggregatedSamples.count) points", systemImage: "chart.xyaxis.line")
890
                        .font(.caption2)
891
                        .foregroundColor(.secondary)
892
                }
893
            }
894
        }
895
        .padding(12)
896
        .meterCard(
897
            tint: sessionTint,
898
            fillOpacity: isSelected ? 0.16 : (isOpen ? 0.14 : 0.08),
899
            strokeOpacity: isSelected ? 0.22 : (isOpen ? 0.30 : 0.14),
900
            cornerRadius: 14
901
        )
902
    }
903

            
904
    private func closedSessions(for chargedDevice: ChargedDeviceSummary) -> [ChargeSessionSummary] {
905
        chargedDevice.sessions.filter { !$0.status.isOpen }
906
    }
907

            
908
    private func availableTabs(for chargedDevice: ChargedDeviceSummary) -> [DetailTab] {
909
        if chargedDevice.isCharger {
910
            return [.overview, .standby, .settings]
911
        }
912
        return [.overview, .sessions, .trends, .settings]
913
    }
914

            
915
    private func displayedTab(from tabs: [DetailTab]) -> DetailTab {
916
        if tabs.contains(selectedTab) {
917
            return selectedTab
918
        }
919
        return tabs.first ?? .overview
920
    }
921

            
922
    private func ensureSelectedTabExists(for chargedDevice: ChargedDeviceSummary) {
923
        let tabs = availableTabs(for: chargedDevice)
924
        if !tabs.contains(selectedTab) {
925
            selectedTab = tabs.first ?? .overview
926
        }
927
    }
928

            
929
    private func title(for tab: DetailTab) -> String {
930
        switch tab {
931
        case .overview:
932
            return "Overview"
933
        case .standby:
934
            return "Standby"
935
        case .sessions:
936
            return "Sessions"
937
        case .trends:
938
            return "Trends"
939
        case .settings:
940
            return "Settings"
941
        }
942
    }
943

            
944
    private func systemImage(for tab: DetailTab) -> String {
945
        switch tab {
946
        case .overview:
947
            return "house.fill"
948
        case .standby:
949
            return "bolt.badge.clock"
950
        case .sessions:
951
            return "clock.arrow.trianglehead.counterclockwise.rotate.90"
952
        case .trends:
953
            return "chart.xyaxis.line"
954
        case .settings:
955
            return "gearshape.fill"
956
        }
957
    }
958

            
959
    private func detailBackground(for chargedDevice: ChargedDeviceSummary) -> some View {
960
        LinearGradient(
961
            colors: [tint(for: chargedDevice).opacity(0.18), Color.clear],
962
            startPoint: .topLeading,
963
            endPoint: .bottomTrailing
964
        )
965
        .ignoresSafeArea()
966
    }
967

            
968
    private func tint(for chargedDevice: ChargedDeviceSummary) -> Color {
969
        switch chargedDevice.deviceClass {
970
        case .iphone:
971
            return .blue
972
        case .watch:
973
            return .green
974
        case .powerbank:
975
            return .orange
976
        case .charger:
977
            return .pink
978
        case .other:
979
            return .secondary
980
        }
981
    }
982

            
983
    private func statusTint(for session: ChargeSessionSummary) -> Color {
984
        switch session.status {
985
        case .active:
986
            return .green
987
        case .paused:
988
            return .orange
989
        case .completed:
990
            return .teal
991
        case .abandoned:
992
            return .secondary
993
        }
994
    }
995

            
996
    private func sessionDurationText(_ session: ChargeSessionSummary) -> String {
997
        let formatter = DateComponentsFormatter()
998
        let effectiveDuration = max(session.effectiveDuration, 0)
999
        formatter.allowedUnits = effectiveDuration >= 3600 ? [.hour, .minute] : [.minute, .second]
1000
        formatter.unitsStyle = .abbreviated
1001
        formatter.zeroFormattingBehavior = .dropAll
1002
        return formatter.string(from: effectiveDuration) ?? "0m"
1003
    }
1004

            
1005
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
1006
        if wattHours >= 1000 {
1007
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
1008
        }
1009
        return "\(wattHours.format(decimalDigits: 2)) Wh"
1010
    }
1011

            
1012
    private var standbyMeasurementMeters: [AppData.MeterSummary] {
1013
        appData.meterSummaries.filter { $0.meter != nil }
1014
    }
1015

            
1016
    private func completionCurrentDescription(
1017
        for chargedDevice: ChargedDeviceSummary,
1018
        sessionKind: ChargeSessionKind
1019
    ) -> String {
1020
        if let configuredCurrent = chargedDevice.configuredCompletionCurrentAmps(for: sessionKind) {
1021
            if let learnedCurrent = chargedDevice.learnedCompletionCurrentAmps(for: sessionKind),
1022
               abs(configuredCurrent - learnedCurrent) >= 0.01 {
1023
                return "\(configuredCurrent.format(decimalDigits: 2)) A configured • \(learnedCurrent.format(decimalDigits: 2)) A learned"
1024
            }
1025
            return "\(configuredCurrent.format(decimalDigits: 2)) A configured"
1026
        }
1027

            
1028
        if let learnedCurrent = chargedDevice.learnedCompletionCurrentAmps(for: sessionKind) {
1029
            return "\(learnedCurrent.format(decimalDigits: 2)) A learned"
1030
        }
1031

            
1032
        return "Learning"
1033
    }
1034

            
1035
    private func completionCurrentLabel(
1036
        for chargedDevice: ChargedDeviceSummary,
1037
        sessionKind: ChargeSessionKind
1038
    ) -> String {
1039
        let showsTransport = chargedDevice.shouldShowChargingTransport(sessionKind.chargingTransportMode)
1040
        let showsState = chargedDevice.shouldShowChargingStateMode(sessionKind.chargingStateMode)
1041

            
1042
        switch (showsTransport, showsState) {
1043
        case (true, true):
1044
            return "\(sessionKind.shortTitle) Stop Current"
1045
        case (true, false):
1046
            return "\(sessionKind.chargingTransportMode.title) Stop Current"
1047
        case (false, true):
1048
            return "\(sessionKind.chargingStateMode.title) Stop Current"
1049
        case (false, false):
1050
            return "Stop Current"
1051
        }
1052
    }
1053

            
1054
    private func completionSessionKinds(for chargedDevice: ChargedDeviceSummary) -> [ChargeSessionKind] {
1055
        chargedDevice.supportedChargingModes.flatMap { chargingTransportMode in
1056
            chargedDevice.supportedChargingStateModes.map { chargingStateMode in
1057
                ChargeSessionKind(
1058
                    chargingTransportMode: chargingTransportMode,
1059
                    chargingStateMode: chargingStateMode
1060
                )
1061
            }
1062
        }
1063
    }
1064

            
1065
    private func deleteSelectedSessions() {
1066
        for id in selectedSessionIDs {
1067
            _ = appData.deleteChargeSession(sessionID: id)
1068
        }
1069
        selectedSessionIDs.removeAll()
1070
        sessionSelectMode = false
1071
    }
1072

            
1073
    private func showEditor() {
1074
        editorVisibility = true
1075
    }
1076

            
1077
    private func showDeleteConfirmation() {
1078
        deleteConfirmationVisibility = true
1079
    }
1080

            
1081
    private var deletionTitle: String {
1082
        appData.chargedDeviceSummary(id: chargedDeviceID)?.isCharger == true ? "charger" : "device"
1083
    }
1084

            
1085
    private var deletionMessage: String {
1086
        if appData.chargedDeviceSummary(id: chargedDeviceID)?.isCharger == true {
1087
            return "This removes the charger from the library and unlinks it from wireless sessions that used it."
1088
        }
1089
        return "This removes the device and its stored charging history from the library."
1090
    }
1091

            
1092
}