# Statistics Window - Feature Documentation

## 🎯 Overview

The Statistics window provides a comprehensive dashboard for viewing conversion analytics with charts, KPIs, and trend analysis.

---

## 📊 Features

### 1. **Header with Period Switcher**

Located at top right with "Show this" label:
```
Show this [Day | Week | Month | Year]
```

- Segmented control (pill-shaped)
- Four options: Day, Week, Month, Year
- Changes entire dashboard when switched
- Default: Week

### 2. **KPI Metrics Row**

Four key performance indicators displayed horizontally:

**Conversions**
- Total number of conversions in period
- Icon: `arrow.triangle.2.circlepath`
- Shows percentage change vs previous period

**Characters**
- Total characters converted
- Icon: `textformat.abc`
- Shows percentage change vs previous period

**Heb → Eng**
- Conversions from Hebrew to English
- Icon: `arrow.forward`
- Shows percentage change vs previous period

**Eng → Heb**
- Conversions from English to Hebrew
- Icon: `arrow.backward`
- Shows percentage change vs previous period

**Percentage Change Indicators:**
- ↑ Green for positive growth
- ↓ Red for decline
- Compares to previous equivalent period

### 3. **Line Chart**

Multi-line chart showing conversion trends over time:

**Two Lines:**
- **Blue line:** Heb → Eng conversions
- **Orange line:** Eng → Heb conversions

**Features:**
- Smooth curves (Catmull-Rom interpolation)
- Semi-transparent area fill under lines
- Gridlines for easy reading
- Date labels on X-axis
- Count labels on Y-axis
- Legend with colored squares

**X-Axis (Date range varies by period):**
- **Day:** 24 hours
- **Week:** 7 days
- **Month:** 30 days
- **Year:** 12 months

**Empty State:**
- Shows when no data available
- Displays icon, headline, and help text
- Encourages user to start using the app

### 4. **Footer**

- **Close button:** Dismisses window (Escape key)
- **Reset Statistics button:** Clears all data (with confirmation)

---

## 🎨 Design Details

### Window
- **Size:** 750 x 600 pixels
- **Style:** Resizable with title bar
- **Icon:** `chart.line.uptrend.xyaxis`

### KPI Cards
- Background: Light gray (`Color.secondary.opacity(0.06)`)
- Border radius: 12px
- Equal width distribution
- Padding: 16px internal, 16px between cards

### Chart
- Height: 250px
- Uses Swift Charts framework
- Colors: Blue (#007AFF) and Orange (#FF9500)
- Area opacity: 0.1

### Typography
- **Window title:** `.title2.bold()`
- **Section headers:** `.headline`
- **KPI values:** `.system(size: 32, weight: .bold)`
- **KPI labels:** `.caption.uppercase`
- **Change indicators:** `.caption`

---

## 💻 Technical Implementation

### Data Sources

**Current Period Stats:**
```swift
settings.statistics.stats(for: selectedPeriod)
```

**Previous Period Stats:**
Calculated by filtering conversions from the previous equivalent time range for comparison.

**Chart Data:**
Generated by grouping conversions into time buckets based on selected period.

### Data Models

**ChartDataPoint:**
```swift
struct ChartDataPoint: Identifiable {
    let id: UUID
    let date: Date
    let count: Int
    let direction: String // "Heb → Eng" or "Eng → Heb"
}
```

**PeriodStats:**
Already defined in `Settings.swift`:
```swift
struct PeriodStats {
    let totalConversions: Int
    let fromCounts: [String: Int]
    let toCounts: [String: Int]
    let totalCharacters: Int
}
```

---

## 🧮 Calculations

### Percentage Change Formula
```
change = ((current - previous) / previous) × 100
```

Special cases:
- If previous = 0 and current > 0: Show 100%
- If previous = 0 and current = 0: Show 0%

### Time Buckets

**Day (24 hours):**
- 24 buckets (1 per hour)
- X-axis: Hour labels

**Week (7 days):**
- 7 buckets (1 per day)
- X-axis: Day labels (e.g., "Mon", "Tue")

**Month (30 days):**
- 30 buckets (1 per day)
- X-axis: Date labels (e.g., "Dec 1", "Dec 2")

**Year (12 months):**
- 12 buckets (1 per month)
- X-axis: Month labels (e.g., "Jan", "Feb")

---

## 🔧 Usage

### Opening the Window

**From Menu Bar:**
1. Click LangToLang icon in menu bar
2. Click "Statistics…"
3. Window opens centered on screen

**Keyboard Shortcut:**
None (can be added: ⌘⇧S)

### Changing Time Period

1. Click the segmented control at top right
2. Choose Day, Week, Month, or Year
3. All metrics and chart update instantly

### Resetting Data

1. Click "Reset Statistics" button
2. Confirm in alert dialog
3. All statistics permanently deleted

---

## 📱 Menu Integration

The menu bar no longer shows inline statistics. Instead:

**Old (v1.5.1):**
```
┌──────────────────────┐
│ Day                  │
│ Week             ✓   │
│ Month                │
│ Year                 │
│ ──────────────────── │
│   47 conversions     │
│   1,284 characters   │
│   → Hebrew: 28       │
└──────────────────────┘
```

**New (v1.5.2):**
```
┌──────────────────────────┐
│ ✓ Enabled                │
│ ────────────────────────  │
│ 📊 Statistics…           │
│ ────────────────────────  │
│ ⌨️ U.S. ↔ Hebrew         │
│ ────────────────────────  │
│ ⚙️ Preferences…     ⌘,   │
│ ────────────────────────  │
│ ✉️ Feedback…             │
│ ℹ️ About…                │
│ ────────────────────────  │
│ ⏻ Quit              ⌘Q   │
└──────────────────────────┘
```

---

## ✅ Benefits

### User Experience
- **More space:** Full window dedicated to statistics
- **Better visualization:** Professional charts instead of text
- **Trends visible:** See patterns over time
- **Easy comparison:** Previous period changes shown
- **Clean menu:** Menu bar remains simple

### Technical
- **Uses Swift Charts:** Native Apple framework
- **Performant:** Efficient data grouping
- **Maintainable:** Clear separation of concerns
- **Extensible:** Easy to add more metrics

---

## 🎨 Visual Examples

### KPI Card Structure
```
┌─────────────────────────┐
│ 🔄 CONVERSIONS          │
│                         │
│ 47                      │  ← Big, bold number
│                         │
│ ↑ 88%                   │  ← Green/red change indicator
└─────────────────────────┘
```

### Chart Example
```
Conversion Trends
──────────────────────────────────
│
30 │            ╱─╲
   │          ╱     ╲       ─ Heb → Eng
20 │     ╱─╲╱         ╲    ─ Eng → Heb
   │   ╱                ╲
10 │ ╱                    ╲
   │
 0 └─────────────────────────
   Mon Tue Wed Thu Fri Sat Sun

Legend: ■ Heb → Eng  ■ Eng → Heb
```

---

## 🐛 Edge Cases Handled

1. **No data:** Shows empty state with helpful message
2. **Zero previous period:** Shows 100% or 0% appropriately
3. **Negative growth:** Displays with down arrow and red color
4. **Single language pair:** Works with any language combination
5. **Window already open:** Closes and reopens (brings to front)

---

## 🚀 Future Enhancements

### Short Term
- Export data as CSV
- Custom date range selector
- Keyboard shortcut (⌘⇧S)
- Print support

### Medium Term
- More chart types (bar, pie)
- Day-of-week analysis
- Peak usage hours
- Language pair breakdown

### Long Term
- Goal setting
- Streak tracking
- Achievements/badges
- Data sync between devices

---

## 📊 Sample Data Flow

```
User converts text
       ↓
Settings.shared.recordConversion()
       ↓
ConversionRecord saved with:
  - timestamp
  - fromLanguage
  - toLanguage
  - characterCount
       ↓
StatisticsView reads conversions
       ↓
Filters by selected period
       ↓
Groups into time buckets
       ↓
Displays in chart + KPIs
```

---

## 📝 Files Modified

### New Files
- `StatisticsView.swift` - Complete statistics window

### Modified Files
- `AppDelegate.swift`
  - Added `statisticsWindow` property
  - Added `showStatistics()` method
  - Replaced inline stats with menu item
  - Removed `getPeriodShortName()` helper

---

## 🧪 Testing Checklist

- [ ] Window opens centered at 750x600
- [ ] Period switcher changes all data
- [ ] KPI cards show correct values
- [ ] Change percentages calculate correctly
- [ ] Chart displays two lines with proper colors
- [ ] Chart shows correct date range for each period
- [ ] Legend displays properly
- [ ] Empty state shows when no data
- [ ] Reset button works with confirmation
- [ ] Window resizes properly
- [ ] Escape key closes window
- [ ] Menu item has icon
- [ ] No inline stats in menu anymore

---

**This is professional, dashboard-style analytics!** 📊✨

