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

            
8
import SwiftUI
9

            
10
struct ChargedDeviceDetailView: View {
Bogdan Timofte authored a month ago
11
    private enum DetailTab: Hashable {
12
        case overview
13
        case standby
14
        case sessions
15
        case trends
16
        case settings
17
    }
18

            
Bogdan Timofte authored a month ago
19
    @EnvironmentObject private var appData: AppData
20
    @Environment(\.dismiss) private var dismiss
Bogdan Timofte authored a month ago
21

            
Bogdan Timofte authored a month ago
22
    @State private var editorVisibility = false
23
    @State private var deleteConfirmationVisibility = false
Bogdan Timofte authored a month ago
24
    @State private var selectedTab: DetailTab = .overview
Bogdan Timofte authored a month ago
25

            
26
    let chargedDeviceID: UUID
27

            
28
    var body: some View {
29
        Group {
30
            if let chargedDevice = appData.chargedDeviceSummary(id: chargedDeviceID) {
Bogdan Timofte authored a month ago
31
                tabbedDetailView(chargedDevice)
Bogdan Timofte authored a month ago
32
                .navigationTitle(chargedDevice.name)
33
                .toolbar {
34
                    ToolbarItemGroup(placement: .primaryAction) {
Bogdan Timofte authored a month ago
35
                        Button("Edit", action: showEditor)
36
                        Button(role: .destructive, action: showDeleteConfirmation) {
Bogdan Timofte authored a month ago
37
                            Image(systemName: "trash")
38
                        }
39
                    }
40
                }
41
            } else {
42
                Text("This device is no longer available.")
43
                    .foregroundColor(.secondary)
44
                    .navigationTitle("Device")
45
            }
46
        }
47
        .sheet(isPresented: $editorVisibility) {
48
            if let chargedDevice = appData.chargedDeviceSummary(id: chargedDeviceID) {
Bogdan Timofte authored a month ago
49
                if chargedDevice.isCharger {
Bogdan Timofte authored a month ago
50
                    ChargerEditorSheetView(chargedDevice: chargedDevice)
51
                        .environmentObject(appData)
Bogdan Timofte authored a month ago
52
                } else {
53
                    ChargedDeviceEditorSheetView(
54
                        meterMACAddress: nil,
55
                        chargedDevice: chargedDevice
56
                    )
57
                    .environmentObject(appData)
58
                }
Bogdan Timofte authored a month ago
59
            }
60
        }
61
        .confirmationDialog("Delete \(deletionTitle)?", isPresented: $deleteConfirmationVisibility, titleVisibility: .visible) {
62
            Button("Delete", role: .destructive) {
63
                if appData.deleteChargedDevice(id: chargedDeviceID) {
64
                    dismiss()
65
                }
66
            }
67
            Button("Cancel", role: .cancel) {}
68
        } message: {
69
            Text(deletionMessage)
70
        }
71
    }
72

            
Bogdan Timofte authored a month ago
73
    private func tabbedDetailView(_ chargedDevice: ChargedDeviceSummary) -> some View {
74
        GeometryReader { proxy in
75
            let tabs = availableTabs(for: chargedDevice)
76
            let displayedTab = displayedTab(from: tabs)
77
            let tabBarPresentation = AdaptiveTabBarPresentation.standard(for: proxy.size)
78

            
79
            VStack(spacing: 0) {
80
                ChargedDeviceDetailTabBarView(
81
                    tabs: tabs,
82
                    selection: $selectedTab,
83
                    tint: tint(for: chargedDevice),
84
                    presentation: tabBarPresentation,
85
                    title: title(for:),
86
                    systemImage: systemImage(for:)
87
                )
88

            
89
                ScrollView {
90
                    tabContent(displayedTab, chargedDevice: chargedDevice)
91
                        .padding()
92
                }
93
                .id(displayedTab)
94
                .transition(.opacity.combined(with: .move(edge: .trailing)))
95
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
96
            }
97
            .animation(.easeInOut(duration: 0.22), value: displayedTab)
98
            .animation(.easeInOut(duration: 0.22), value: tabs)
99
        }
100
        .background(detailBackground(for: chargedDevice))
101
        .onAppear {
102
            ensureSelectedTabExists(for: chargedDevice)
103
        }
104
        .onChange(of: chargedDevice.isCharger) { _ in
105
            ensureSelectedTabExists(for: chargedDevice)
106
        }
107
    }
108

            
109
    @ViewBuilder
110
    private func tabContent(_ tab: DetailTab, chargedDevice: ChargedDeviceSummary) -> some View {
111
        VStack(spacing: 18) {
112
            switch tab {
113
            case .overview:
114
                overviewTab(chargedDevice)
115
            case .standby:
116
                standbyTab(chargedDevice)
117
            case .sessions:
118
                sessionsTab(chargedDevice)
119
            case .trends:
120
                trendsTab(chargedDevice)
121
            case .settings:
122
                settingsTab(chargedDevice)
123
            }
124
        }
125
    }
126

            
127
    @ViewBuilder
128
    private func overviewTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
129
        headerCard(chargedDevice)
130
        insightsCard(chargedDevice)
131

            
132
        if let activeSession = chargedDevice.activeSession {
133
            activeSessionSummaryCard(activeSession, chargedDevice: chargedDevice)
134
        }
135
    }
136

            
137
    @ViewBuilder
138
    private func standbyTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
139
        standbyPowerCard(chargedDevice)
140
    }
141

            
142
    @ViewBuilder
143
    private func sessionsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
144
        if let activeSession = chargedDevice.activeSession {
145
            activeSessionSummaryCard(activeSession, chargedDevice: chargedDevice)
146
        }
147

            
148
        if !closedSessions(for: chargedDevice).isEmpty {
149
            sessionHistorySummaryCard(chargedDevice)
150
        } else if chargedDevice.activeSession == nil {
151
            emptyStateCard(
152
                title: "No Sessions",
Bogdan Timofte authored a month ago
153
                message: "Charging sessions will appear here after this device is used in a recording.",
Bogdan Timofte authored a month ago
154
                tint: .teal
155
            )
156
        }
157
    }
158

            
159
    @ViewBuilder
160
    private func trendsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
161
        if !chargedDevice.capacityHistory.isEmpty {
162
            capacityEvolutionCard(chargedDevice)
163
        }
164

            
165
        if !chargedDevice.typicalCurve.isEmpty {
166
            typicalCurveCard(chargedDevice)
167
        }
168

            
169
        if chargedDevice.capacityHistory.isEmpty && chargedDevice.typicalCurve.isEmpty {
170
            emptyStateCard(
171
                title: "Learning Trends",
172
                message: "Capacity history and charge curves will appear after enough completed sessions are available.",
173
                tint: .blue
174
            )
175
        }
176
    }
177

            
178
    @ViewBuilder
179
    private func settingsTab(_ chargedDevice: ChargedDeviceSummary) -> some View {
180
        settingsCard(chargedDevice)
181
    }
182

            
Bogdan Timofte authored a month ago
183
    private func headerCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
184
        HStack(alignment: .top, spacing: 18) {
185
            ChargedDeviceQRCodeView(qrIdentifier: chargedDevice.qrIdentifier, side: 118)
186

            
187
            VStack(alignment: .leading, spacing: 10) {
Bogdan Timofte authored a month ago
188
                ChargedDeviceIdentityLabelView(
189
                    chargedDevice: chargedDevice,
190
                    iconPointSize: 22
191
                )
192
                .font(.title3.weight(.bold))
Bogdan Timofte authored a month ago
193

            
Bogdan Timofte authored a month ago
194
                Text(chargedDevice.identityTitle)
Bogdan Timofte authored a month ago
195
                    .font(.subheadline.weight(.semibold))
196
                    .foregroundColor(.secondary)
197

            
198
                if let meterMAC = chargedDevice.lastAssociatedMeterMAC {
199
                    Text("Default meter: \(meterMAC)")
200
                        .font(.caption)
201
                        .foregroundColor(.secondary)
202
                }
203

            
204
                Text(chargedDevice.qrIdentifier)
205
                    .font(.caption2.monospaced())
206
                    .foregroundColor(.secondary)
207
                    .textSelection(.enabled)
208
            }
209

            
210
            Spacer(minLength: 0)
211
        }
212
        .frame(maxWidth: .infinity, alignment: .leading)
213
        .padding(18)
214
        .meterCard(tint: tint(for: chargedDevice), fillOpacity: 0.20, strokeOpacity: 0.26, cornerRadius: 20)
215
    }
216

            
Bogdan Timofte authored a month ago
217
    private func settingsCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
218
        MeterInfoCardView(title: "Settings", tint: tint(for: chargedDevice)) {
219
            MeterInfoRowView(
220
                label: "Kind",
221
                value: chargedDevice.isCharger ? "Charger" : chargedDevice.deviceClass.title
222
            )
223
            MeterInfoRowView(label: "Template", value: chargedDevice.identityTitle)
224
            MeterInfoRowView(label: "QR ID", value: chargedDevice.qrIdentifier)
225

            
226
            if let meterMAC = chargedDevice.lastAssociatedMeterMAC {
227
                MeterInfoRowView(label: "Default Meter", value: meterMAC)
228
            }
229

            
230
            MeterInfoRowView(label: "Created", value: chargedDevice.createdAt.format())
231
            MeterInfoRowView(label: "Updated", value: chargedDevice.updatedAt.format())
232

            
233
            Divider()
234

            
235
            Button(action: showEditor) {
236
                Label("Edit \(chargedDevice.isCharger ? "Charger" : "Device")", systemImage: "pencil")
237
                    .font(.subheadline.weight(.semibold))
238
                    .frame(maxWidth: .infinity)
239
                    .padding(.vertical, 10)
240
                    .meterCard(tint: tint(for: chargedDevice), fillOpacity: 0.16, strokeOpacity: 0.22, cornerRadius: 14)
241
            }
242
            .buttonStyle(.plain)
243

            
244
            Button(role: .destructive, action: showDeleteConfirmation) {
245
                Label("Delete \(chargedDevice.isCharger ? "Charger" : "Device")", systemImage: "trash")
246
                    .font(.subheadline.weight(.semibold))
247
                    .frame(maxWidth: .infinity)
248
                    .padding(.vertical, 10)
249
                    .meterCard(tint: .red, fillOpacity: 0.10, strokeOpacity: 0.18, cornerRadius: 14)
250
            }
251
            .buttonStyle(.plain)
252
        }
253
    }
254

            
255
    private func emptyStateCard(title: String, message: String, tint: Color) -> some View {
256
        VStack(alignment: .leading, spacing: 8) {
257
            Text(title)
258
                .font(.headline)
259
            Text(message)
260
                .font(.footnote)
261
                .foregroundColor(.secondary)
262
                .fixedSize(horizontal: false, vertical: true)
263
        }
264
        .frame(maxWidth: .infinity, alignment: .leading)
265
        .padding(18)
266
        .meterCard(tint: tint, fillOpacity: 0.12, strokeOpacity: 0.18, cornerRadius: 18)
267
    }
268

            
Bogdan Timofte authored a month ago
269
    private func insightsCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
270
        MeterInfoCardView(title: "Insights", tint: tint(for: chargedDevice)) {
Bogdan Timofte authored a month ago
271
            if chargedDevice.isCharger {
272
                chargerInsights(chargedDevice)
273
            } else {
274
                deviceInsights(chargedDevice)
275
            }
276

            
277
            if let notes = chargedDevice.notes, !notes.isEmpty {
278
                Divider()
279
                Text(notes)
280
                    .font(.footnote)
281
                    .foregroundColor(.secondary)
282
                    .frame(maxWidth: .infinity, alignment: .leading)
283
            }
284
        }
285
    }
286

            
287
    @ViewBuilder
288
    private func deviceInsights(_ chargedDevice: ChargedDeviceSummary) -> some View {
Bogdan Timofte authored a month ago
289
        if chargedDevice.hasMultipleChargingStateModes {
290
            MeterInfoRowView(
291
                label: "Charge Modes",
292
                value: chargedDevice.chargingStateAvailability.title
293
            )
294
        }
295
        if chargedDevice.hasMultipleChargingTransports {
296
            MeterInfoRowView(
297
                label: "Charging Support",
298
                value: chargedDevice.supportedChargingModes.map(\.title).joined(separator: " + ")
299
            )
300
        }
301
        if chargedDevice.showsWirelessProfileDetails {
Bogdan Timofte authored a month ago
302
            MeterInfoRowView(
Bogdan Timofte authored a month ago
303
                label: "Wireless Profile",
304
                value: chargedDevice.wirelessChargingProfile.title
Bogdan Timofte authored a month ago
305
            )
Bogdan Timofte authored a month ago
306
        }
307

            
308
        ForEach(completionSessionKinds(for: chargedDevice), id: \.rawValue) { sessionKind in
Bogdan Timofte authored a month ago
309
            MeterInfoRowView(
Bogdan Timofte authored a month ago
310
                label: completionCurrentLabel(for: chargedDevice, sessionKind: sessionKind),
Bogdan Timofte authored a month ago
311
                value: completionCurrentDescription(for: chargedDevice, sessionKind: sessionKind)
Bogdan Timofte authored a month ago
312
            )
Bogdan Timofte authored a month ago
313
        }
314
        MeterInfoRowView(
315
            label: "Estimated Capacity",
316
            value: chargedDevice.estimatedBatteryCapacityWh.map { "\($0.format(decimalDigits: 2)) Wh" } ?? "Not enough data"
317
        )
318
        if let wiredCapacity = chargedDevice.wiredEstimatedBatteryCapacityWh {
Bogdan Timofte authored a month ago
319
            if chargedDevice.hasMultipleChargingTransports {
320
                MeterInfoRowView(
321
                    label: "Wired Capacity",
322
                    value: "\(wiredCapacity.format(decimalDigits: 2)) Wh"
323
                )
324
            }
Bogdan Timofte authored a month ago
325
        }
326
        if let wirelessCapacity = chargedDevice.wirelessEstimatedBatteryCapacityWh {
Bogdan Timofte authored a month ago
327
            if chargedDevice.hasMultipleChargingTransports {
328
                MeterInfoRowView(
329
                    label: "Wireless Capacity",
330
                    value: "\(wirelessCapacity.format(decimalDigits: 2)) Wh"
331
                )
332
            }
Bogdan Timofte authored a month ago
333
        }
Bogdan Timofte authored a month ago
334
        if let wirelessEfficiencyFactor = chargedDevice.wirelessChargerEfficiencyFactor,
335
           chargedDevice.showsWirelessProfileDetails {
Bogdan Timofte authored a month ago
336
            MeterInfoRowView(
337
                label: "Wireless Efficiency",
338
                value: "\(Int((wirelessEfficiencyFactor * 100).rounded()))%"
339
            )
340
        }
341
        MeterInfoRowView(
342
            label: "Charge Sessions",
343
            value: "\(chargedDevice.sessionCount)"
344
        )
345
    }
Bogdan Timofte authored a month ago
346

            
Bogdan Timofte authored a month ago
347
    @ViewBuilder
348
    private func chargerInsights(_ chargedDevice: ChargedDeviceSummary) -> some View {
Bogdan Timofte authored a month ago
349
        if let chargerType = chargedDevice.chargerType {
350
            MeterInfoRowView(
351
                label: "Type",
352
                value: chargerType.title
353
            )
354
        }
Bogdan Timofte authored a month ago
355
        if !chargedDevice.chargerObservedVoltageSelections.isEmpty {
Bogdan Timofte authored a month ago
356
            MeterInfoRowView(
Bogdan Timofte authored a month ago
357
                label: "Observed Voltages",
358
                value: chargedDevice.chargerObservedVoltageSelections
359
                    .map { "\($0.format(decimalDigits: 1)) V" }
360
                    .joined(separator: ", ")
Bogdan Timofte authored a month ago
361
            )
Bogdan Timofte authored a month ago
362
        }
363
        if let chargerIdleCurrentAmps = chargedDevice.chargerIdleCurrentAmps {
Bogdan Timofte authored a month ago
364
            MeterInfoRowView(
Bogdan Timofte authored a month ago
365
                label: "Idle Current",
366
                value: "\(chargerIdleCurrentAmps.format(decimalDigits: 2)) A"
Bogdan Timofte authored a month ago
367
            )
Bogdan Timofte authored a month ago
368
        }
369
        if let chargerEfficiencyFactor = chargedDevice.chargerEfficiencyFactor {
Bogdan Timofte authored a month ago
370
            MeterInfoRowView(
Bogdan Timofte authored a month ago
371
                label: "Efficiency",
372
                value: "\(Int((chargerEfficiencyFactor * 100).rounded()))%"
Bogdan Timofte authored a month ago
373
            )
Bogdan Timofte authored a month ago
374
        }
375
        if let chargerMaximumPowerWatts = chargedDevice.chargerMaximumPowerWatts {
376
            MeterInfoRowView(
377
                label: "Max Power",
378
                value: "\(chargerMaximumPowerWatts.format(decimalDigits: 2)) W"
379
            )
380
        }
Bogdan Timofte authored a month ago
381
        if let latestStandbyPowerMeasurement = chargedDevice.latestStandbyPowerMeasurement {
382
            MeterInfoRowView(
383
                label: "Standby Power",
384
                value: "\(latestStandbyPowerMeasurement.averagePowerWatts.format(decimalDigits: 3)) W"
385
            )
386
            MeterInfoRowView(
387
                label: "Standby Projection",
388
                value: standbyEnergyLabel(latestStandbyPowerMeasurement.projectedYearlyEnergyWh) + " / year"
389
            )
390
        }
Bogdan Timofte authored a month ago
391
        MeterInfoRowView(
392
            label: "Wireless Sessions",
393
            value: "\(chargedDevice.sessionCount)"
394
        )
Bogdan Timofte authored a month ago
395

            
396
    }
397

            
Bogdan Timofte authored a month ago
398
    private func standbyPowerCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
399
        let latestMeasurement = chargedDevice.latestStandbyPowerMeasurement
400

            
401
        return MeterInfoCardView(
402
            title: "Standby Power",
403
            tint: .orange
404
        ) {
405
            if standbyMeasurementMeters.isEmpty {
406
                Text("Connect a meter first. Standby measurement is launched from a live meter feed, so only currently available meters can be selected here.")
407
                    .font(.footnote)
408
                    .foregroundColor(.secondary)
409
                    .frame(maxWidth: .infinity, alignment: .leading)
410
            } else {
411
                NavigationLink(
412
                    destination: ChargerStandbyPowerWizardView(
413
                        preferredChargerID: chargedDevice.id,
414
                        locksChargerSelection: true
415
                    )
416
                ) {
417
                    Label("New Measurement", systemImage: "plus.circle.fill")
418
                        .font(.subheadline.weight(.semibold))
419
                        .foregroundColor(.orange)
420
                }
421
                .buttonStyle(.plain)
422
            }
423

            
424
            if let latestMeasurement {
425
                Divider()
426

            
427
                NavigationLink(
428
                    destination: ChargerStandbyPowerMeasurementDetailView(
429
                        chargerID: chargedDevice.id,
430
                        measurementID: latestMeasurement.id
431
                    )
432
                ) {
433
                    VStack(alignment: .leading, spacing: 8) {
434
                        HStack {
435
                            Text("Latest Measurement")
436
                                .font(.subheadline.weight(.semibold))
437
                                .foregroundColor(.primary)
438
                            Spacer()
439
                            Text("\(latestMeasurement.averagePowerWatts.format(decimalDigits: 3)) W")
440
                                .font(.subheadline.weight(.bold))
441
                                .foregroundColor(.primary)
442
                                .monospacedDigit()
443
                        }
444

            
445
                        Text(
446
                            "\(latestMeasurement.endedAt.format()) • \(latestMeasurement.sampleCount) samples • \(standbyEnergyLabel(latestMeasurement.projectedYearlyEnergyWh)) / year"
447
                        )
448
                        .font(.caption)
449
                        .foregroundColor(.secondary)
450
                    }
451
                }
452
                .buttonStyle(.plain)
453
            }
454

            
455
            if chargedDevice.standbyPowerMeasurements.isEmpty == false {
456
                Divider()
457

            
458
                NavigationLink(
459
                    destination: ChargerStandbyPowerMeasurementsView(chargerID: chargedDevice.id)
460
                ) {
461
                    Label("View Saved Measurements", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
462
                        .font(.subheadline.weight(.semibold))
463
                        .foregroundColor(.blue)
464
                }
465
                .buttonStyle(.plain)
466
            }
467
        }
468
    }
469

            
Bogdan Timofte authored a month ago
470
    private func activeSessionSummaryCard(
Bogdan Timofte authored a month ago
471
        _ activeSession: ChargeSessionSummary,
472
        chargedDevice: ChargedDeviceSummary
473
    ) -> some View {
Bogdan Timofte authored a month ago
474
        NavigationLink(
Bogdan Timofte authored a month ago
475
            destination: ChargeSessionDetailView(
476
                chargedDeviceID: chargedDevice.id,
477
                sessionID: activeSession.id
478
            )
Bogdan Timofte authored a month ago
479
        ) {
480
            VStack(alignment: .leading, spacing: 14) {
481
                HStack(alignment: .firstTextBaseline) {
482
                    VStack(alignment: .leading, spacing: 4) {
483
                        Text("Current Session")
484
                            .font(.headline)
485
                            .foregroundColor(.primary)
486
                        Text(activeSession.status.title)
487
                            .font(.caption.weight(.semibold))
488
                            .foregroundColor(statusTint(for: activeSession))
489
                    }
Bogdan Timofte authored a month ago
490

            
Bogdan Timofte authored a month ago
491
                    Spacer()
Bogdan Timofte authored a month ago
492

            
Bogdan Timofte authored a month ago
493
                    Image(systemName: "chevron.right")
494
                        .font(.caption.weight(.semibold))
495
                        .foregroundColor(.secondary)
Bogdan Timofte authored a month ago
496
                }
497

            
Bogdan Timofte authored a month ago
498
                LazyVGrid(columns: activeSessionSummaryColumns, spacing: 8) {
499
                    activeSessionMetricCell(
500
                        label: "Energy",
501
                        value: "\(activeSession.effectiveOrMeasuredEnergyWh.format(decimalDigits: 2)) Wh",
502
                        tint: .teal
503
                    )
504
                    activeSessionMetricCell(
505
                        label: "Duration",
506
                        value: sessionDurationText(activeSession),
507
                        tint: .orange
508
                    )
509
                    if let maximumObservedPowerWatts = activeSession.maximumObservedPowerWatts {
510
                        activeSessionMetricCell(
511
                            label: "Max Power",
512
                            value: "\(maximumObservedPowerWatts.format(decimalDigits: 2)) W",
513
                            tint: .blue
514
                        )
515
                    }
516
                    if let batteryPrediction = chargedDevice.batteryLevelPrediction(for: activeSession) {
517
                        activeSessionMetricCell(
518
                            label: "Battery",
519
                            value: "\(batteryPrediction.predictedPercent.format(decimalDigits: 0))%",
520
                            tint: .green
521
                        )
522
                    } else if let targetBatteryPercent = activeSession.targetBatteryPercent {
523
                        activeSessionMetricCell(
524
                            label: "Target",
525
                            value: "\(targetBatteryPercent.format(decimalDigits: 0))%",
526
                            tint: .indigo
527
                        )
528
                    }
Bogdan Timofte authored a month ago
529
                }
530

            
Bogdan Timofte authored a month ago
531
                Text("Started \(activeSession.startedAt.format())")
532
                    .font(.caption)
Bogdan Timofte authored a month ago
533
                    .foregroundColor(.secondary)
534
            }
Bogdan Timofte authored a month ago
535
        }
536
        .buttonStyle(.plain)
537
        .padding(18)
538
        .meterCard(tint: statusTint(for: activeSession), fillOpacity: 0.16, strokeOpacity: 0.22, cornerRadius: 18)
539
    }
Bogdan Timofte authored a month ago
540

            
Bogdan Timofte authored a month ago
541
    private var activeSessionSummaryColumns: [GridItem] {
542
        [
543
            GridItem(.flexible(minimum: 92), spacing: 8),
544
            GridItem(.flexible(minimum: 92), spacing: 8)
545
        ]
546
    }
Bogdan Timofte authored a month ago
547

            
Bogdan Timofte authored a month ago
548
    private func activeSessionMetricCell(label: String, value: String, tint: Color) -> some View {
549
        VStack(alignment: .leading, spacing: 4) {
550
            Text(label)
551
                .font(.caption2)
552
                .foregroundColor(.secondary)
553
            Text(value)
554
                .font(.footnote.weight(.semibold))
555
                .foregroundColor(.primary)
556
                .monospacedDigit()
557
                .lineLimit(1)
558
                .minimumScaleFactor(0.8)
Bogdan Timofte authored a month ago
559
        }
Bogdan Timofte authored a month ago
560
        .frame(maxWidth: .infinity, alignment: .leading)
561
        .padding(10)
562
        .meterCard(tint: tint, fillOpacity: 0.08, strokeOpacity: 0.12, cornerRadius: 12)
Bogdan Timofte authored a month ago
563
    }
564

            
565
    private func capacityEvolutionCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
566
        VStack(alignment: .leading, spacing: 12) {
567
            Text("Capacity Evolution")
568
                .font(.headline)
569

            
570
            ForEach(chargedDevice.capacityHistory.suffix(6)) { point in
571
                HStack {
572
                    Text(point.timestamp.format())
573
                        .font(.caption)
574
                        .foregroundColor(.secondary)
575
                    Spacer()
Bogdan Timofte authored a month ago
576
                    if chargedDevice.shouldShowChargingTransport(point.chargingTransportMode) {
577
                        Text(point.chargingTransportMode.title)
578
                            .font(.caption2)
579
                            .foregroundColor(.secondary)
580
                        Text("•")
581
                            .foregroundColor(.secondary)
582
                    }
Bogdan Timofte authored a month ago
583
                    Text("\(point.capacityWh.format(decimalDigits: 2)) Wh")
584
                        .font(.footnote.weight(.semibold))
585
                }
586
            }
587
        }
588
        .frame(maxWidth: .infinity, alignment: .leading)
589
        .padding(18)
590
        .meterCard(tint: .orange, fillOpacity: 0.14, strokeOpacity: 0.20, cornerRadius: 18)
591
    }
592

            
593
    private func typicalCurveCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
594
        VStack(alignment: .leading, spacing: 12) {
595
            Text("Typical Charge Curve")
596
                .font(.headline)
597

            
598
            ForEach(chargedDevice.typicalCurve) { point in
599
                HStack {
600
                    Text("\(point.percentBin)%")
601
                        .font(.footnote.weight(.semibold))
602
                    Spacer()
603
                    Text("\(point.averageEnergyWh.format(decimalDigits: 2)) Wh")
604
                        .font(.caption.weight(.semibold))
605
                    Text("•")
606
                        .foregroundColor(.secondary)
607
                    Text("\(point.sampleCount) sample\(point.sampleCount == 1 ? "" : "s")")
608
                        .font(.caption2)
609
                        .foregroundColor(.secondary)
610
                }
611
            }
612
        }
613
        .frame(maxWidth: .infinity, alignment: .leading)
614
        .padding(18)
615
        .meterCard(tint: .blue, fillOpacity: 0.14, strokeOpacity: 0.20, cornerRadius: 18)
616
    }
617

            
Bogdan Timofte authored a month ago
618
    private func sessionHistorySummaryCard(_ chargedDevice: ChargedDeviceSummary) -> some View {
619
        let sessions = closedSessions(for: chargedDevice)
620
        let latestSession = sessions.first
621
        let totalEnergyWh = sessions.reduce(0) { $0 + $1.effectiveOrMeasuredEnergyWh }
Bogdan Timofte authored a month ago
622

            
Bogdan Timofte authored a month ago
623
        return MeterInfoCardView(title: "Session History", tint: .teal) {
624
            MeterInfoRowView(label: "Closed Sessions", value: "\(sessions.count)")
625
            MeterInfoRowView(label: "Total Energy", value: "\(totalEnergyWh.format(decimalDigits: 2)) Wh")
626
            if let latestSession {
627
                MeterInfoRowView(label: "Latest", value: latestSession.startedAt.format())
628
            }
Bogdan Timofte authored a month ago
629

            
Bogdan Timofte authored a month ago
630
            NavigationLink(
631
                destination: ChargedDeviceSessionsView(chargedDeviceID: chargedDevice.id)
632
            ) {
633
                Label("Manage Sessions", systemImage: "clock.arrow.trianglehead.counterclockwise.rotate.90")
634
                    .font(.subheadline.weight(.semibold))
635
                    .frame(maxWidth: .infinity)
636
                    .padding(.vertical, 10)
637
                    .meterCard(tint: .teal, fillOpacity: 0.16, strokeOpacity: 0.22, cornerRadius: 14)
Bogdan Timofte authored a month ago
638
            }
Bogdan Timofte authored a month ago
639
            .buttonStyle(.plain)
Bogdan Timofte authored a month ago
640
        }
641
    }
642

            
Bogdan Timofte authored a month ago
643
    private func closedSessions(for chargedDevice: ChargedDeviceSummary) -> [ChargeSessionSummary] {
644
        chargedDevice.sessions.filter { !$0.status.isOpen }
Bogdan Timofte authored a month ago
645
    }
646

            
Bogdan Timofte authored a month ago
647
    private func availableTabs(for chargedDevice: ChargedDeviceSummary) -> [DetailTab] {
648
        if chargedDevice.isCharger {
Bogdan Timofte authored a month ago
649
            return [.overview, .standby, .settings]
Bogdan Timofte authored a month ago
650
        }
Bogdan Timofte authored a month ago
651
        return [.overview, .sessions, .trends, .settings]
652
    }
Bogdan Timofte authored a month ago
653

            
Bogdan Timofte authored a month ago
654
    private func displayedTab(from tabs: [DetailTab]) -> DetailTab {
655
        if tabs.contains(selectedTab) {
656
            return selectedTab
Bogdan Timofte authored a month ago
657
        }
Bogdan Timofte authored a month ago
658
        return tabs.first ?? .overview
659
    }
660

            
661
    private func ensureSelectedTabExists(for chargedDevice: ChargedDeviceSummary) {
662
        let tabs = availableTabs(for: chargedDevice)
663
        if !tabs.contains(selectedTab) {
664
            selectedTab = tabs.first ?? .overview
Bogdan Timofte authored a month ago
665
        }
Bogdan Timofte authored a month ago
666
    }
667

            
668
    private func title(for tab: DetailTab) -> String {
669
        switch tab {
670
        case .overview:
671
            return "Overview"
672
        case .standby:
673
            return "Standby"
674
        case .sessions:
675
            return "Sessions"
676
        case .trends:
677
            return "Trends"
678
        case .settings:
679
            return "Settings"
Bogdan Timofte authored a month ago
680
        }
Bogdan Timofte authored a month ago
681
    }
Bogdan Timofte authored a month ago
682

            
Bogdan Timofte authored a month ago
683
    private func systemImage(for tab: DetailTab) -> String {
684
        switch tab {
685
        case .overview:
686
            return "house.fill"
687
        case .standby:
688
            return "bolt.badge.clock"
689
        case .sessions:
690
            return "clock.arrow.trianglehead.counterclockwise.rotate.90"
691
        case .trends:
692
            return "chart.xyaxis.line"
693
        case .settings:
694
            return "gearshape.fill"
695
        }
696
    }
697

            
698
    private func detailBackground(for chargedDevice: ChargedDeviceSummary) -> some View {
699
        LinearGradient(
700
            colors: [tint(for: chargedDevice).opacity(0.18), Color.clear],
701
            startPoint: .topLeading,
702
            endPoint: .bottomTrailing
703
        )
704
        .ignoresSafeArea()
Bogdan Timofte authored a month ago
705
    }
706

            
707
    private func tint(for chargedDevice: ChargedDeviceSummary) -> Color {
708
        switch chargedDevice.deviceClass {
709
        case .iphone:
710
            return .blue
711
        case .watch:
712
            return .green
713
        case .powerbank:
714
            return .orange
715
        case .charger:
716
            return .pink
717
        case .other:
718
            return .secondary
719
        }
720
    }
721

            
Bogdan Timofte authored a month ago
722
    private func statusTint(for session: ChargeSessionSummary) -> Color {
723
        switch session.status {
724
        case .active:
725
            return .green
726
        case .paused:
727
            return .orange
728
        case .completed:
729
            return .teal
730
        case .abandoned:
731
            return .secondary
732
        }
733
    }
734

            
735
    private func sessionDurationText(_ session: ChargeSessionSummary) -> String {
736
        let formatter = DateComponentsFormatter()
737
        let effectiveDuration = max(session.effectiveDuration, 0)
738
        formatter.allowedUnits = effectiveDuration >= 3600 ? [.hour, .minute] : [.minute, .second]
739
        formatter.unitsStyle = .abbreviated
740
        formatter.zeroFormattingBehavior = .dropAll
741
        return formatter.string(from: effectiveDuration) ?? "0m"
742
    }
743

            
Bogdan Timofte authored a month ago
744
    private func standbyEnergyLabel(_ wattHours: Double) -> String {
745
        if wattHours >= 1000 {
746
            return "\((wattHours / 1000).format(decimalDigits: 3)) kWh"
747
        }
748
        return "\(wattHours.format(decimalDigits: 2)) Wh"
749
    }
750

            
751
    private var standbyMeasurementMeters: [AppData.MeterSummary] {
752
        appData.meterSummaries.filter { $0.meter != nil }
753
    }
754

            
Bogdan Timofte authored a month ago
755
    private func completionCurrentDescription(
756
        for chargedDevice: ChargedDeviceSummary,
Bogdan Timofte authored a month ago
757
        sessionKind: ChargeSessionKind
Bogdan Timofte authored a month ago
758
    ) -> String {
Bogdan Timofte authored a month ago
759
        if let configuredCurrent = chargedDevice.configuredCompletionCurrentAmps(for: sessionKind) {
760
            if let learnedCurrent = chargedDevice.learnedCompletionCurrentAmps(for: sessionKind),
Bogdan Timofte authored a month ago
761
               abs(configuredCurrent - learnedCurrent) >= 0.01 {
762
                return "\(configuredCurrent.format(decimalDigits: 2)) A configured • \(learnedCurrent.format(decimalDigits: 2)) A learned"
763
            }
764
            return "\(configuredCurrent.format(decimalDigits: 2)) A configured"
765
        }
766

            
Bogdan Timofte authored a month ago
767
        if let learnedCurrent = chargedDevice.learnedCompletionCurrentAmps(for: sessionKind) {
Bogdan Timofte authored a month ago
768
            return "\(learnedCurrent.format(decimalDigits: 2)) A learned"
769
        }
770

            
771
        return "Learning"
772
    }
773

            
Bogdan Timofte authored a month ago
774
    private func completionCurrentLabel(
775
        for chargedDevice: ChargedDeviceSummary,
776
        sessionKind: ChargeSessionKind
777
    ) -> String {
778
        let showsTransport = chargedDevice.shouldShowChargingTransport(sessionKind.chargingTransportMode)
779
        let showsState = chargedDevice.shouldShowChargingStateMode(sessionKind.chargingStateMode)
780

            
781
        switch (showsTransport, showsState) {
782
        case (true, true):
783
            return "\(sessionKind.shortTitle) Stop Current"
784
        case (true, false):
785
            return "\(sessionKind.chargingTransportMode.title) Stop Current"
786
        case (false, true):
787
            return "\(sessionKind.chargingStateMode.title) Stop Current"
788
        case (false, false):
789
            return "Stop Current"
790
        }
791
    }
792

            
Bogdan Timofte authored a month ago
793
    private func completionSessionKinds(for chargedDevice: ChargedDeviceSummary) -> [ChargeSessionKind] {
794
        chargedDevice.supportedChargingModes.flatMap { chargingTransportMode in
795
            chargedDevice.supportedChargingStateModes.map { chargingStateMode in
796
                ChargeSessionKind(
797
                    chargingTransportMode: chargingTransportMode,
798
                    chargingStateMode: chargingStateMode
799
                )
800
            }
801
        }
802
    }
803

            
Bogdan Timofte authored a month ago
804
    private func showEditor() {
805
        editorVisibility = true
Bogdan Timofte authored a month ago
806
    }
807

            
Bogdan Timofte authored a month ago
808
    private func showDeleteConfirmation() {
809
        deleteConfirmationVisibility = true
Bogdan Timofte authored a month ago
810
    }
811

            
Bogdan Timofte authored a month ago
812
    private var deletionTitle: String {
813
        appData.chargedDeviceSummary(id: chargedDeviceID)?.isCharger == true ? "charger" : "device"
814
    }
815

            
816
    private var deletionMessage: String {
817
        if appData.chargedDeviceSummary(id: chargedDeviceID)?.isCharger == true {
818
            return "This removes the charger from the library and unlinks it from wireless sessions that used it."
819
        }
820
        return "This removes the device and its stored charging history from the library."
821
    }
822

            
Bogdan Timofte authored a month ago
823
}