# UI Alignment to API Documentation

Mapare UI ↔ Operații documentate. Status implementare şi TODO-uri pentru a alinia UI la documentație.

---

## 1. Charging Monitoring

**Documentație:** [ChargingMonitoring.md](./ChargingMonitoring.md)

### Responsabilități
- ✅ Start → record → end sesiune
- ✅ Colectare măsurători ~1Hz
- ✅ Calculul energiei totale
- ⚠️ Timeout logic (incomplete)

### UI Components

| File | Status | Alignment | TODO |
|---|---|---|---|
| `MeterChargeRecordTabView.swift` | ✅ Exists | Good | Document timeout handling |
| `ChargeRecordSheetView.swift` | ✅ Exists | Fair | Add measurement count UI |
| `ChargeSessionCompletionSheetView.swift` | ✅ Exists | Fair | Show isolation interval |
| `BatteryCheckpointEditorSheetView.swift` | ✅ Exists | Good | Add stdDev visualization |

### Current UI Flow

```
MeterChargeRecordTabView
├─ [Start recording button]
├─ [Live power graph]
├─ [Energy counter (Wh)]
├─ [Duration counter]
└─ [Stop recording button]
   └─ ChargeRecordSheetView
      ├─ [Completion details]
      ├─ [Battery checkpoints]
      ├─ [Charger selection]
      └─ [Save/discard]
```

### Needed Alignments

1. **Invariant validation display**
   - MUST show error if start without device
   - SHOULD show warning if session > 24h
   - SHOULD show warning if measurement gap > 5min

2. **Measurement monitoring**
   - SHOULD display sample count (ex: "324 samples")
   - SHOULD show last update time
   - MAY show power trend (trending up/down/stable)

3. **Isolation visualization**
   - After stop, show isolated interval on curve
   - Highlight [real_start, real_end]
   - Show pre/post noise regions

---

## 2. Capacity Measurement

**Documentație:** [CapacityMeasurement.md](./CapacityMeasurement.md)

### Responsabilități
- ✅ Learning din discharge sessions
- ⚠️ Health tracking (not visible in UI)
- ⚠️ Weighted average (calculated, not displayed)

### UI Components

| File | Status | Alignment | TODO |
|---|---|---|---|
| `ChargeSessionDetailView.swift` | ✅ Exists | Poor | Add capacity learning |
| `ChargedDeviceSettingsView.swift` | ✅ Exists | Poor | Show measured vs rated capacity |
| — | ❌ Missing | — | Battery health indicator |
| — | ❌ Missing | — | Capacity trend graph |

### Current UI

```
ChargeSessionDetailView
├─ [Session info: date, duration, energy]
├─ [Device/charger info]
└─ [Checkpoint list]
```

### Needed Alignments

1. **Capacity learning indicator**
   - IF session = complete discharge (0% → 100%)
     - Show: "Capacity learning: 2950 mAh ✓"
   - ELSE
     - Show: "Partial discharge (15%), no capacity learning"

2. **Battery health display**
   - NEW section: "Battery Health"
     ```
     Measured capacity:    2950 mAh
     Rated capacity:       3000 mAh
     Health:               98% ✓
     ```
   - IF health < 80%: Show warning "Aged battery"

3. **Multiple measurement history**
   - NEW tab: "Capacity History"
   - Show last 5 discharge cycles
   - Chart: capacity over time
   - Show trend: "Stable" / "Degrading" / "Improving"

---

## 3. Charge Curve Isolation

**Documentație:** [ChargeCurveIsolation.md](./ChargeCurveIsolation.md)

### Responsabilități
- ✅ Detect start (power threshold)
- ✅ Detect end (trickle charge)
- ⚠️ Visual feedback (weak)

### UI Components

| File | Status | Alignment | TODO |
|---|---|---|---|
| `ChargeRecordSheetView.swift` | ✅ Exists | Fair | Add isolation visualization |
| `TimeSeriesChart.swift` | ✅ Exists | Good | Highlight isolated region |

### Current UI

```
ChargeRecordSheetView
├─ [Total energy]
├─ [Duration]
└─ [Checkpoints]
```

### Needed Alignments

1. **Isolated interval visualization**
   - After completion, show original curve with:
     ```
     Power (W)
     20├──────────────────────
       │ NOISE (discarded)
     10├──────┐
       │ ISOLATED REGION ████████
      5├──────┘
       │ NOISE (discarded)
     0└──────────────────────
     ```

2. **Detection feedback**
   - Show: "Auto-isolated [10:15–10:45] (30 min)"
   - If manual override: "Custom selection [10:16–10:43]"

3. **Noise estimation**
   - Show: "Pre-charge noise: 15% of total"
   - Show: "Post-charge noise: 5% of total"

---

## 4. Charge Curve Storage

**Documentație:** [ChargeCurveStorage.md](./ChargeCurveStorage.md)

### Responsabilități
- ✅ Persist to Core Data
- ✅ CloudKit sync
- ⚠️ Compression visible to user

### UI Components

| File | Status | Alignment | TODO |
|---|---|---|---|
| `ChargedDeviceSessionsView.swift` | ✅ Exists | Good | Show compression status |
| `ChargeSessionDetailView.swift` | ✅ Exists | Good | Show sample count |

### Current UI

```
ChargedDeviceSessionsView
├─ [Session list (sorted by date)]
└─ [Each row: date, duration, energy]
```

### Needed Alignments

1. **Compression indicator**
   - IF session < 7 days: "Full resolution (3600 samples)"
   - ELSE IF session < 365 days: "Downsampled (360 samples)"
   - ELSE: "Archived (metadata only)"

2. **Sync status**
   - NEW badge: ☁️ (synced) / ⏳ (pending) / ⚠️ (conflict)

3. **Storage estimate**
   - Footer: "Storage: 2.4 MB (on device) + 1.2 MB (iCloud)"

---

## 5. Consumption Measurement

**Documentație:** [ConsumptionMeasurement.md](./ConsumptionMeasurement.md)

### Responsabilități
- ✅ Select arbitrary interval
- ✅ Tail trimming (graph selection)
- ✅ Display statistics
- ⚠️ Predictions (weak implementation)
- ✅ Discard measurements

### UI Components

| File | Status | Alignment | TODO |
|---|---|---|---|
| `ConsumptionMonitorView.swift` | ✅ Exists | Good | Strengthen predictions |
| `TimeSeriesChart.swift` | ✅ Exists | Good | Add interval selection |

### Current UI

```
ConsumptionMonitorView
├─ [Meter selection]
├─ [Active session card]
├─ [Live metrics (Power, Energy, Time)]
├─ [Aggregation duration selector (300s default)]
├─ [Inventory list]
└─ [Saved sessions]
```

### Needed Alignments

1. **Tail trimming improvements**
   - Current: "Stop" button
   - NEW: Interactive graph with draggable endpoints
   ```
   Power (W)
   20├──────────────────
     │ ◄─ drag start
     │  [selected region]
   10├──────────────────► drag end
     │
   0 └──────────────────
     10:00   10:30   11:00
   ```

2. **Prediction display**
   - Current: Only shows "Aggregation duration" selector
   - NEW: Add prediction section
   ```
   Measured (10:00–10:30): 12.5W avg
   Predict next 30 min:     12.5Wh ±2.5Wh (80% confidence)
   Predict next 24h:        300Wh ±120Wh (40% confidence ⚠️)
   ```

3. **Statistics card**
   - Current: Only total energy + duration
   - NEW: Add table
   ```
   Total Energy:     12.5 Wh
   Avg Power:        25 W
   Peak Power:       32 W
   Min Power:        15 W
   Variance (σ):     ±3.2 W
   Measurement #:    1800 samples
   ```

4. **Measurement discard confirmation**
   - Current: ✓ (button exists)
   - NEW: Show "Discarding measurements, keeping stats..."

---

## 6. Idle Consumption Measurement

**Documentație:** [IdleConsumptionMeasurement.md](./IdleConsumptionMeasurement.md)

### Responsabilități
- ❌ NOT implemented in UI
- ❌ NO idle detection
- ❌ NO idle profiles

### Current State

```
Status: ❌ MISSING
```

### Required Implementation

#### New Views

1. **IdleConsumptionSetupView**
   ```
   ┌─────────────────────────────┐
   │ Measure Idle Consumption    │
   ├─────────────────────────────┤
   │ Device:      [iPhone 15  ▼] │
   │ Charger:     [USB-C 20W ▼] │
   │ Battery:     [100% ✓]      │
   ├─────────────────────────────┤
   │  [Start measurement]        │
   └─────────────────────────────┘
   ```

2. **IdleConsumptionMonitorView**
   ```
   ┌──────────────────────────────┐
   │ Recording idle consumption...│
   ├──────────────────────────────┤
   │ Power (W)              5 W   │
   │  Trend: ↘ (stabilizing)     │
   │                              │
   │ Time elapsed:      00:15:32  │
   │                              │
   │ Status:  ✓ Idle detected     │
   │         (power < 5W, stable) │
   │                              │
   │  [Confirm]   [Discard]       │
   └──────────────────────────────┘
   ```

3. **IdleConsumptionReviewView**
   ```
   ┌──────────────────────────────┐
   │ Idle Profile (Adjust)        │
   ├──────────────────────────────┤
   │ Power (W)                    │
   │ 5 ├─────────────────         │
   │   │     ◄─ slide to adjust   │
   │ 0 │ ████████████► idle       │
   │   └────────────────────      │
   │   10:15      10:45           │
   │                              │
   │ Idle Power:    0.25 W        │
   │ Duration:      30 min        │
   │ Confidence:    85% ✓         │
   │                              │
   │ [Save profile]   [Retry]     │
   └──────────────────────────────┘
   ```

4. **DeviceIdleProfilesView**
   ```
   ┌──────────────────────────────┐
   │ Idle Profiles                │
   ├──────────────────────────────┤
   │ iPhone 15:                   │
   │  └─ USB-C 20W:     0.25 W   │
   │  └─ MagSafe:       0.20 W   │
   │                              │
   │ iPad Pro:                    │
   │  └─ USB-C 30W:     0.45 W   │
   │                              │
   │  [Measure new]   [Edit]      │
   └──────────────────────────────┘
   ```

#### Integration Points

1. **ChargeSessionCompletionSheetView**
   - Add row: "Auto-terminate when: [idle power + 50%]"
   - When user selects idle profile, pre-fill

2. **MeterChargeRecordTabView**
   - Show idle indicator when power drops below threshold
   - "Idle detected, session can auto-terminate"

3. **ChargedDeviceSettingsView**
   - NEW section: "Idle Consumption Profile"
   - Show measured idle power per charger
   - Link to "Measure idle..."

---

## 7. System Core Operations

**Documentație:**
- [Operations.md](./Operations.md)
- [CloudKitSync.md](./CloudKitSync.md)
- [BluetoothDiscovery.md](./BluetoothDiscovery.md)

### Status: ✅ Mostly implemented

| Component | UI File | Status |
|---|---|---|
| BT Discovery | `SidebarMeterCardView.swift` | ✅ Good |
| Connection | `MeterHomeTabView.swift` | ✅ Good |
| CloudKit sync | (implicit) | ✅ Good |

### Needed Alignments

1. **CloudKit sync status display**
   - Current: No visible indicator
   - NEW: Badge in meter card "☁️ synced @ 10:45"

2. **Connection retry display**
   - Current: Just shows "Offline"
   - NEW: "Offline (retry in 8s...)" or "Reconnecting..."

3. **Discovery throttling indicator**
   - MAY: Show "Last scan: 45s ago" in debug view

---

## Summary Table

| Operation | Documentație | UI Status | Alignment | Priority |
|---|---|---|---|---|
| Charging Monitoring | ✅ | ✅ Impl | Fair | Medium |
| Capacity Learning | ✅ | ⚠️ Partial | Poor | High |
| Curve Isolation | ✅ | ✅ Impl | Fair | Medium |
| Curve Storage | ✅ | ✅ Impl | Good | Low |
| Consumption Meas. | ✅ | ✅ Impl | Good | Low |
| **Idle Consumption** | ✅ | ❌ Missing | — | **High** |
| Cloud Sync | ✅ | ✅ Impl | Good | Low |
| BT Discovery | ✅ | ✅ Impl | Good | Low |

---

## Alignment Checklist

### High Priority (implement next)

- [ ] Idle Consumption Measurement (all 4 new views)
- [ ] Capacity Learning display in ChargeSessionDetailView
- [ ] Battery Health section in ChargedDeviceSettingsView
- [ ] Curve Isolation visualization in ChargeRecordSheetView

### Medium Priority (refine)

- [ ] Consumption prediction UI (confidence bounds)
- [ ] Measurement validation warnings
- [ ] Compression status indicators

### Low Priority (nice-to-have)

- [ ] Discovery throttling display
- [ ] Retry countdown in connection status
- [ ] Storage estimate footer

---

## Implementation Guide

### For each operation:

1. **Read documentation** (`ChargingMonitoring.md`, etc.)
2. **Identify required UI** (sections above)
3. **Check invariants** (MUST/SHOULD/MAY)
4. **Implement/update views**
5. **Add validation errors**
6. **Test with unit tests**
7. **Link to documentation in comments**

Example comment in code:
```swift
// See: Documentation/API Reference/ChargingMonitoring.md
// MUST: recordMeasurement fails if sessionState < active
if !session.isActive {
    throw SessionError.invalidState
}
```

---

## Notes

- This document is a living checklist
- Update as UI aligns with docs
- Link each UI file to relevant docs
- Mark `// DOCUMENTED` in code for traced invariants
