     1→# CLAUDE.md - ProductivityHub-iOS
     2→
     3→This file provides guidance to Claude Code (claude.ai/code) when working with this iOS app.
     4→
     5→## 🎯 Project Overview
     6→
     7→**ProductivityHub-iOS** is a unified productivity application that consolidates features from three separate apps:
     8→- **ToDoMax-iOS** - Task management with subtasks and importance flags
     9→- **FocusWriter** - Deep work timer (2 hours) + Pomodoro mode with task categories
    10→- **JournalCurator** - AI-powered journaling with auto-categorization
    11→
    12→**Goal:** Create a single, streamlined iOS app that eliminates redundancy and provides an intuitive productivity experience with local-first storage.
    13→
    14→## 📊 Project Stats
    15→
    16→- **Lines of Code:** ~2,500+ (consolidated + polish improvements)
    17→- **Original Code:** ~8,000 lines across 3 apps
    18→- **Code Reduction:** 70% from original 3 apps
    19→- **Dependencies:** 0 (pure SwiftUI + Foundation + UIKit for haptics)
    20→- **Minimum iOS:** 17.0+
    21→- **Platforms:** iPhone, iPad, Mac Catalyst
    22→- **Architecture:** MVVM with @Observable
    23→- **Storage:** UserDefaults with 3-layer backup system
    24→- **Backend:** None (local-first)
    25→- **Production Status:** 100% Ready 🚀
    26→- **Features:** 14 improvements across 2 polish sessions
    27→
    28→## 🏗 Architecture
    29→
    30→### MVVM Pattern with SwiftUI
    31→
    32→```
    33→ProductivityHub-iOS/
    34→├── ProductivityHubApp.swift          # @main entry point (with haptic prep)
    35→├── HapticManager.swift               # Optimized haptic feedback system
    36→├── App/
    37→│   └── MainTabView.swift             # Adaptive nav: TabView (iPhone) / NavigationSplitView (iPad/Mac)
    38→├── Models/                           # Unified data models
    39→│   ├── Task.swift                    # Task management (ToDoMax + FocusWriter)
    40→│   ├── WorkSession.swift             # Focus sessions (FocusWriter)
    41→│   ├── JournalEntry.swift            # Journal entries (JournalCurator)
    42→│   ├── Tag.swift                     # Unified tagging system
    43→│   └── Template.swift                # Quick capture templates
    44→├── Services/                         # Business logic & persistence
    45→│   ├── DataManager.swift             # Singleton with 3-layer backup + haptics
    46→│   ├── TimerService.swift            # Deep Work + Pomodoro timer + background support
    47→│   ├── NotificationService.swift     # Local notifications
    48→│   └── ExportService.swift           # Data export (JSON/CSV)
    49→├── Components/                       # Reusable UI components
    50→│   ├── OnboardingTip.swift           # Onboarding hints system + manager
    51→│   └── ToastView.swift               # Toast notifications
    52→├── Features/                         # Feature-based organization
    53→│   ├── Focus/
    54→│   │   └── FocusView.swift           # Tab 1: Timer (with onboarding)
    55→│   ├── Tasks/
    56→│   │   └── TasksView.swift           # Tab 2: Task management (progressive disclosure)
    57→│   ├── Journal/
    58→│   │   └── JournalView.swift         # Tab 3: Journaling (vertical metadata)
    59→│   ├── Insights/
    60→│   │   └── InsightsView.swift        # Tab 4: Statistics (time range picker)
    61→│   └── Settings/
    62→│       └── SettingsView.swift        # Tab 5: Settings (reset onboarding)
    63→└── Info.plist
    64→```
    65→
    66→### Key Architectural Decisions
    67→
    68→1. **@Observable instead of @ObservableObject**
    69→   - Using iOS 17+ `@Observable` macro for DataManager
    70→   - Simpler syntax, automatic dependency tracking
    71→   - More performant than `@Published` properties
    72→
    73→2. **Singleton DataManager**
    74→   - Single source of truth for all data
    75→   - Shared across all views via `@EnvironmentObject`
    76→   - Handles all CRUD operations and persistence
    77→
    78→3. **3-Layer Backup System (from ToDoMax)**
    79→   - Primary key: `ProductivityHub_Tasks`
    80→   - Backup 1: `ProductivityHub_Tasks_backup1`
    81→   - Backup 2: `ProductivityHub_Tasks_backup2`
    82→   - Cascading recovery on data corruption
    83→
    84→4. **Feature-Based Folder Structure**
    85→   - Each feature (Focus, Tasks, Journal) in own folder
    86→   - Makes navigation easier as app grows
    87→   - Clear separation of concerns
    88→
    89→5. **Adaptive Navigation (iPad/Mac)**
    90→   - iPhone: TabView with 5 tabs (standard bottom bar)
    91→   - iPad/Mac: NavigationSplitView with sidebar
    92→   - `horizontalSizeClass` environment variable for detection
    93→   - Seamless experience across all Apple platforms
    94→
    95→## 💻 iPad & Mac Support
    96→
    97→### Adaptive Navigation
    98→
    99→The app automatically adapts its navigation pattern based on screen size:
   100→
   101→**iPhone (Compact Width):**
   102→```swift
   103→TabView(selection: $quickActionManager.selectedTab) {
   104→    FocusView().tabItem { Label("Focus", systemImage: "timer") }
   105→    TasksView().tabItem { Label("Tasks", systemImage: "checklist") }
   106→    // ... 5 tabs total
   107→}
   108→```
   109→
   110→**iPad/Mac (Regular Width):**
   111→```swift
   112→NavigationSplitView {
   113→    List(NavigationItem.allCases, selection: $selectedItem) { item in
   114→        Label(item.rawValue, systemImage: item.icon)
   115→    }
   116→} detail: {
   117→    // Content view based on selection
   118→}
   119→```
   120→
   121→### Mac Menu Bar Commands
   122→
   123→Mac Catalyst includes native menu bar commands:
   124→
   125→| Menu | Command | Shortcut |
   126→|------|---------|----------|
   127→| File | New Task | ⌘N |
   128→| File | New Journal Entry | ⇧⌘N |
   129→| File | Start Focus Session | ⇧⌘F |
   130→| View | Show Focus | ⌘1 |
   131→| View | Show Tasks | ⌘2 |
   132→| View | Show Journal | ⌘3 |
   133→| View | Show Insights | ⌘4 |
   134→| View | Show Settings | ⌘, |
   135→
   136→**Implementation:** `ProductivityHubApp.swift` using `.commands` modifier with `#if targetEnvironment(macCatalyst)`.
   137→
   138→### iPad Keyboard Shortcuts
   139→
   140→Same shortcuts available via external keyboard on iPad:
   141→- ⌘1 through ⌘5 for tab navigation
   142→- Uses hidden button pattern for keyboard capture
   143→
   144→### Platform-Specific Considerations
   145→
   146→**Mac Catalyst:**
   147→- Haptic feedback disabled (not supported)
   148→- Menu bar commands enabled
   149→- Window resizing supported
   150→- Native macOS window controls
   151→
   152→**iPad:**
   153→- Sidebar navigation with split view
   154→- Keyboard shortcuts via external keyboard
   155→- Pointer/trackpad support
   156→
   157→**HapticManager Compatibility:**
   158→```swift
   159→#if !targetEnvironment(macCatalyst)
   160→// Haptic generators only initialized on iOS
   161→private static let lightImpact = UIImpactFeedbackGenerator(style: .light)
   162→#endif
   163→
   164→static func impact(_ style: UIImpactFeedbackGenerator.FeedbackStyle) {
   165→    #if !targetEnvironment(macCatalyst)
   166→    guard isEnabled, supportsHaptics else { return }
   167→    // ... haptic code
   168→    #endif
   169→}
   170→```
   171→
   172→### Building for Different Platforms
   173→
   174→```bash
   175→# iPhone Simulator
   176→xcodebuild -project ProductivityHub-iOS.xcodeproj \
   177→  -scheme ProductivityHub-iOS \
   178→  -sdk iphonesimulator \
   179→  -destination 'platform=iOS Simulator,name=iPhone 17 Pro'
   180→
   181→# iPad Simulator
   182→xcodebuild -project ProductivityHub-iOS.xcodeproj \
   183→  -scheme ProductivityHub-iOS \
   184→  -sdk iphonesimulator \
   185→  -destination 'platform=iOS Simulator,name=iPad Pro 13-inch (M4)'
   186→
   187→# Mac Catalyst
   188→xcodebuild -project ProductivityHub-iOS.xcodeproj \
   189→  -scheme ProductivityHub-iOS \
   190→  -destination 'platform=macOS,variant=Mac Catalyst'
   191→```
   192→
   193→## 📦 Data Models
   194→
   195→### Task (Unified from ToDoMax + FocusWriter)
   196→
   197→```swift
   198→struct Task: Identifiable, Codable, Hashable {
   199→    var id: UUID
   200→    var title: String
   201→    var notes: String
   202→    var isCompleted: Bool
   203→    var isImportant: Bool                    // From ToDoMax
   204→    var priority: TaskPriority               // From FocusWriter (low/medium/high/urgent)
   205→    var category: TaskCategory               // From FocusWriter (8 categories)
   206→    var subtasks: [Subtask]                  // From ToDoMax
   207→    var linkedSessionIds: [UUID]             // Link to WorkSessions
   208→    var tags: [UUID]                         // Link to Tags
   209→    var estimatedDuration: TimeInterval?     // From FocusWriter
   210→    var dueDate: Date?
   211→    var createdAt: Date
   212→    var completedAt: Date?
   213→}
   214→
   215→enum TaskPriority: String, Codable {
   216→    case low, medium, high, urgent
   217→}
   218→
   219→enum TaskCategory: String, Codable {
   220→    case work, personal, health, learning, creative, finance, social, other
   221→}
   222→
   223→struct Subtask: Identifiable, Codable {
   224→    var id: UUID
   225→    var title: String
   226→    var isCompleted: Bool
   227→    var createdAt: Date
   228→}
   229→```
   230→
   231→**Merging Strategy:**
   232→- ToDoMax provided: `isImportant`, `subtasks` (core task features)
   233→- FocusWriter provided: `priority`, `category`, `estimatedDuration`, `linkedSessionIds`
   234→- Combined: Best of both worlds - simple task management + advanced categorization
   235→
   236→### WorkSession (from FocusWriter)
   237→
   238→```swift
   239→struct WorkSession: Identifiable, Codable {
   240→    var id: UUID
   241→    var sessionType: SessionType             // deepWork (2h) / pomodoro (25m) / break
   242→    var duration: TimeInterval               // Actual duration
   243→    var targetDuration: TimeInterval         // Planned duration
   244→    var linkedTaskIds: [UUID]                // Link to Tasks
   245→    var notes: String
   246→    var startTime: Date
   247→    var endTime: Date?
   248→    var wasCompleted: Bool                   // Did they finish?
   249→}
   250→
   251→enum SessionType: String, Codable {
   252→    case deepWork    // 2 hours (default)
   253→    case pomodoro    // 25 minutes
   254→    case break5      // 5 minutes
   255→    case break15     // 15 minutes
   256→}
   257→```
   258→
   259→**Why Keep This Model:**
   260→- FocusWriter had excellent timer implementation
   261→- Tracks both planned and actual time
   262→- Links sessions to tasks for productivity insights
   263→
   264→### JournalEntry (from JournalCurator)
   265→
   266→```swift
   267→struct JournalEntry: Identifiable, Codable {
   268→    var id: UUID
   269→    var content: String
   270→    var title: String
   271→    var category: EntryCategory?             // Auto-detected or manual
   272→    var tags: [UUID]
   273→    var linkedTaskIds: [UUID]                // Optional link to tasks
   274→    var linkedSessionIds: [UUID]             // Optional link to sessions
   275→    var mood: Int?                           // 1-5 scale
   276→    var createdAt: Date
   277→    var modifiedAt: Date
   278→    var isFavorite: Bool
   279→}
   280→
   281→enum EntryCategory: String, Codable {
   282→    case work, personal, gratitude, reflection, goal, achievement, challenge, idea, learning, other
   283→}
   284→```
   285→
   286→**Why Keep This Model:**
   287→- JournalCurator had sophisticated categorization
   288→- Auto-detection of entry type (future AI feature)
   289→- Mood tracking for insights
   290→- Linking to tasks/sessions enables cross-feature insights
   291→
   292→### Tag (Unified)
   293→
   294→```swift
   295→struct Tag: Identifiable, Codable {
   296→    var id: UUID
   297→    var name: String
   298→    var colorHex: String                     // #007AFF format
   299→    var icon: String?                        // SF Symbol name
   300→    var createdAt: Date
   301→}
   302→```
   303→
   304→**System Tags (Pre-populated):**
   305→- Important, Urgent, Personal, Work, Health, Finance, Learning, Creative
   306→
   307→**Why Unified:**
   308→- Both JournalCurator and FocusWriter had tags
   309→- JournalCurator's implementation was more sophisticated (colors + icons)
   310→- Used across Tasks and JournalEntries
   311→
   312→### Template (Quick Capture)
   313→
   314→```swift
   315→struct Template: Identifiable, Codable {
   316→    var id: UUID
   317→    var name: String
   318→    var type: TemplateType                   // task / journal / both
   319→    var icon: String
   320→
   321→    // Task template fields
   322→    var taskTitle: String?
   323→    var taskPriority: TaskPriority?
   324→    var taskCategory: TaskCategory?
   325→
   326→    // Journal template fields
   327→    var journalPrompt: String?
   328→    var journalCategory: EntryCategory?
   329→
   330→    var defaultTags: [UUID]
   331→    var usageCount: Int
   332→}
   333→
   334→enum TemplateType: String, Codable {
   335→    case task, journal, both
   336→}
   337→```
   338→
   339→**System Templates (Pre-populated):**
   340→- Daily Review (journal)
   341→- Quick Task (task)
   342→- Work Task (task)
   343→- Gratitude Entry (journal)
   344→- Goal + Task (both)
   345→
   346→**Why Added:**
   347→- Reduces friction for common actions
   348→- Inspired by JournalCurator's prompts
   349→- Extends to tasks as well
   350→
   351→## 🗄 Data Persistence
   352→
   353→### 3-Layer Backup System (from ToDoMax)
   354→
   355→**Strategy:**
   356→```
   357→Save Operation:
   358→1. Validate new data can be decoded (integrity check)
   359→2. Cascade existing backups: current → backup1, backup1 → backup2
   360→3. Save new data to current key
   361→4. Log operation
   362→
   363→Load Operation:
   364→1. Try primary key → Success? Return
   365→2. Try backup1 key → Success? Restore to primary, return
   366→3. Try backup2 key → Success? Restore to primary + backup1, return
   367→4. No data found → Return default value
   368→```
   369→
   370→**UserDefaults Keys:**
   371→```swift
   372→// Tasks
   373→"ProductivityHub_Tasks"
   374→"ProductivityHub_Tasks_backup1"
   375→"ProductivityHub_Tasks_backup2"
   376→
   377→// WorkSessions
   378→"ProductivityHub_Sessions"
   379→"ProductivityHub_Sessions_backup1"
   380→"ProductivityHub_Sessions_backup2"
   381→
   382→// Journal Entries
   383→"ProductivityHub_Journal"
   384→"ProductivityHub_Journal_backup1"
   385→"ProductivityHub_Journal_backup2"
   386→
   387→// Tags
   388→"ProductivityHub_Tags"
   389→"ProductivityHub_Tags_backup1"
   390→"ProductivityHub_Tags_backup2"
   391→
   392→// Templates
   393→"ProductivityHub_Templates"
   394→"ProductivityHub_Templates_backup1"
   395→"ProductivityHub_Templates_backup2"
   396→```
   397→
   398→**Why UserDefaults Instead of Core Data?**
   399→- Simpler implementation (no migration hassles)
   400→- Faster for small-to-medium datasets (<10MB)
   401→- User chose "Sem Backend" (no backend)
   402→- ToDoMax's backup system proven reliable
   403→- Can migrate to Core Data later if needed
   404→
   405→**Data Validation:**
   406→```swift
   407→// Before saving, verify data can be decoded
   408→guard let encoded = try? JSONEncoder().encode(data) else { return }
   409→guard (try? JSONDecoder().decode(type(of: data).self, from: encoded)) != nil else { return }
   410→```
   411→
   412→## 🎨 UI/UX Design
   413→
   414→### TabView Navigation (5 Tabs)
   415→
   416→1. **Focus** (Timer icon)
   417→   - Large timer display (2h default, 25m Pomodoro)
   418→   - Session type selector
   419→   - Start/Pause/Stop controls
   420→   - Quick task link
   421→   - Session history
   422→
   423→2. **Tasks** (Checklist icon)
   424→   - List with checkboxes
   425→   - Filter: All / Active / Completed / Important
   426→   - Sort: Priority / Due Date / Category
   427→   - Subtask progress indicators
   428→   - Swipe actions: Edit / Delete / Important
   429→
   430→3. **Journal** (Book icon)
   431→   - Chronological list (newest first)
   432→   - Entry cards with excerpts
   433→   - Category/mood indicators
   434→   - Search functionality
   435→   - Filter by category/tags
   436→
   437→4. **Insights** (Chart icon)
   438→   - Current streak (days)
   439→   - Task statistics (completed/pending/overdue)
   440→   - Total focus time (hours)
   441→   - Today's activity summary
   442→   - Charts: Category breakdown, completion trends
   443→
   444→5. **Settings** (Gear icon)
   445→   - Tag management
   446→   - Template management
   447→   - Export data (JSON/CSV)
   448→   - About section
   449→   - Clear all data (danger zone)
   450→
   451→### Color Scheme
   452→
   453→**System Colors (iOS native):**
   454→- Primary: `.blue` (iOS system blue)
   455→- Success: `.green` (completed items)
   456→- Warning: `.orange` (overdue)
   457→- Danger: `.red` (urgent)
   458→- Secondary: `.gray` (low priority)
   459→
   460→**Priority Colors:**
   461→- Low: Gray
   462→- Medium: Blue
   463→- High: Orange
   464→- Urgent: Red
   465→
   466→**Category Colors:**
   467→- Work: Blue
   468→- Personal: Purple
   469→- Health: Pink
   470→- Learning: Teal
   471→- Creative: Orange
   472→- Finance: Green
   473→- Social: Indigo
   474→- Other: Gray
   475→
   476→## 🔧 Key Services
   477→
   478→### DataManager (Singleton)
   479→
   480→**Responsibilities:**
   481→- Load all data on app launch
   482→- Save all data when app goes to background
   483→- Provide CRUD operations for all models
   484→- Calculate statistics (streak, completion rate, etc.)
   485→- Handle 3-layer backup system
   486→
   487→**Usage:**
   488→```swift
   489→@EnvironmentObject var dataManager: DataManager
   490→
   491→// Add task
   492→dataManager.addTask(newTask)
   493→
   494→// Update task
   495→dataManager.updateTask(modifiedTask)
   496→
   497→// Toggle completion
   498→dataManager.toggleTaskCompletion(task)
   499→
   500→// Get statistics
   501→let stats = dataManager.getTaskStatistics()
   502→let streak = dataManager.getStreakDays()
   503→let todayFocus = dataManager.getTotalFocusTime()
   504→```
   505→
   506→### TimerService (@Observable)
   507→
   508→**Responsibilities:**
   509→- Manage timer state (running/paused)
   510→- Track elapsed time
   511→- Handle Deep Work (2h) and Pomodoro (25m) modes
   512→- Auto-stop when target reached
   513→- Create WorkSession records
   514→
   515→**Usage:**
   516→```swift
   517→@StateObject private var timerService = TimerService()
   518→
   519→// Start 2-hour deep work session
   520→timerService.startTimer(type: .deepWork)
   521→
   522→// Start 25-minute Pomodoro
   523→timerService.startTimer(type: .pomodoro)
   524→
   525→// Pause/Resume
   526→timerService.pauseTimer()
   527→timerService.resumeTimer()
   528→
   529→// Stop and save
   530→timerService.stopTimer(save: true)
   531→if let session = timerService.currentSession {
   532→    dataManager.addWorkSession(session)
   533→}
   534→```
   535→
   536→## 🚀 Development Workflow
   537→
   538→### Building the Project
   539→
   540→```bash
   541→# Generate Xcode project (first time)
   542→cd /Users/neog/ProductivityHub-iOS
   543→ruby generate-xcode-project.rb
   544→
   545→# Open in Xcode
   546→open ProductivityHub-iOS.xcodeproj
   547→
   548→# Or build from command line
   549→xcodebuild -project ProductivityHub-iOS.xcodeproj \
   550→  -scheme ProductivityHub-iOS \
   551→  -sdk iphonesimulator \
   552→  -destination 'platform=iOS Simulator,name=iPhone 15 Pro'
   553→```
   554→
   555→### Testing on Simulator
   556→
   557→```bash
   558→# List available simulators
   559→xcrun simctl list devices
   560→
   561→# Boot simulator
   562→xcrun simctl boot <DEVICE_ID>
   563→
   564→# Install app
   565→xcrun simctl install <DEVICE_ID> <PATH_TO_APP>
   566→
   567→# Launch app
   568→xcrun simctl launch <DEVICE_ID> com.yourname.ProductivityHub-iOS
   569→
   570→# View logs
   571→xcrun simctl spawn <DEVICE_ID> log stream --predicate 'process == "ProductivityHub-iOS"'
   572→```
   573→
   574→### Adding New Features
   575→
   576→**Example: Adding a new Task property**
   577→
   578→1. Update `Task.swift` model:
   579→```swift
   580→struct Task {
   581→    // ... existing properties
   582→    var newProperty: String = "default"
   583→}
   584→```
   585→
   586→2. No migration needed (Codable handles it)
   587→3. If old data doesn't have property, defaults will be used
   588→4. Update UI to display/edit new property
   589→
   590→**Example: Adding a new View**
   591→
   592→1. Create new Swift file in appropriate feature folder
   593→2. Import SwiftUI and add to project
   594→3. Add `@EnvironmentObject var dataManager: DataManager` if needed
   595→4. Use `#Preview` for quick testing
   596→
   597→## 📋 Common Tasks
   598→
   599→### Reading Data from DataManager
   600→
   601→```swift
   602→struct MyView: View {
   603→    @EnvironmentObject var dataManager: DataManager
   604→
   605→    var body: some View {
   606→        List(dataManager.tasks) { task in
   607→            Text(task.title)
   608→        }
   609→    }
   610→}
   611→```
   612→
   613→### Creating a Task
   614→
   615→```swift
   616→Button("Add Task") {
   617→    let newTask = Task(
   618→        title: "New Task",
   619→        priority: .medium,
   620→        category: .personal
   621→    )
   622→    dataManager.addTask(newTask)
   623→}
   624→```
   625→
   626→### Filtering Tasks
   627→
   628→```swift
   629→// All incomplete tasks
   630→let activeTasks = dataManager.tasks.filter { !$0.isCompleted }
   631→
   632→// Important tasks
   633→let importantTasks = dataManager.tasks.filter { $0.isImportant }
   634→
   635→// Overdue tasks
   636→let overdueTasks = dataManager.tasks.filter { $0.isOverdue }
   637→
   638→// Tasks by category
   639→let workTasks = dataManager.tasks.filter { $0.category == .work }
   640→```
   641→
   642→### Displaying Statistics
   643→
   644→```swift
   645→let stats = dataManager.getTaskStatistics()
   646→
   647→Text("Completion Rate: \(Int(stats.completionRate))%")
   648→Text("Completed: \(stats.completed) / \(stats.total)")
   649→Text("Pending: \(stats.pending)")
   650→Text("Overdue: \(stats.overdue)")
   651→```
   652→
   653→## 🐛 Common Issues & Solutions
   654→
   655→### Issue: App crashes on launch
   656→
   657→**Cause:** Corrupted data in UserDefaults
   658→
   659→**Solution:**
   660→```swift
   661→// In DataManager, add recovery logic
   662→if tasks.isEmpty && workSessions.isEmpty && journalEntries.isEmpty {
   663→    print("⚠ All data empty - possible corruption")
   664→    // Try manual recovery or reset
   665→}
   666→```
   667→
   668→**Nuclear option:**
   669→```bash
   670→# Clear all UserDefaults for app (simulator)
   671→xcrun simctl spawn booted defaults delete com.yourname.ProductivityHub-iOS
   672→```
   673→
   674→### Issue: Timer doesn't stop automatically
   675→
   676→**Cause:** Timer not invalidated properly
   677→
   678→**Solution:**
   679→```swift
   680→func stopTimer() {
   681→    timer?.invalidate()
   682→    timer = nil  // Important: release reference
   683→    isRunning = false
   684→}
   685→```
   686→
   687→### Issue: Data not saving when app goes to background
   688→
   689→**Cause:** `onReceive` not triggered
   690→
   691→**Solution:**
   692→```swift
   693→// In ProductivityHubApp.swift
   694→.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
   695→    dataManager.saveAllData()
   696→}
   697→
   698→// Also save when app terminates
   699→.onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { _ in
   700→    dataManager.saveAllData()
   701→}
   702→```
   703→
   704→### Issue: Xcode project out of sync with files
   705→
   706→**Cause:** Added/removed files manually
   707→
   708→**Solution:**
   709→```bash
   710→# Regenerate project
   711→ruby generate-xcode-project.rb
   712→# Xcode will ask to reload - click "Reload"
   713→```
   714→
   715→## 📊 Performance Considerations
   716→
   717→### UserDefaults Limits
   718→
   719→- **Practical limit:** 5-10MB recommended
   720→- **Hard limit:** ~40MB (iOS may purge)
   721→- **Our usage:** ~1-5MB typical (thousands of items)
   722→
   723→**Monitoring:**
   724→```swift
   725→let encoder = JSONEncoder()
   726→if let encoded = try? encoder.encode(tasks) {
   727→    let sizeInMB = Double(encoded.count) / 1_048_576
   728→    print("Tasks size: \(sizeInMB) MB")
   729→}
   730→```
   731→
   732→### Memory Optimization
   733→
   734→- Use `[weak self]` in Timer closures
   735→- Invalidate timers when not needed
   736→- Avoid loading all journal entries at once (pagination if >1000)
   737→
   738→### UI Performance
   739→
   740→- Use `List` instead of `ScrollView` + `ForEach` for large lists
   741→- Lazy loading with `.onAppear` for expensive operations
   742→- Debounce search queries
   743→
   744→## 🔮 Future Enhancements
   745→
   746→### Phase 2 (Advanced Features)
   747→
   748→1. **AI Content Parser** (from JournalCurator)
   749→   - Auto-categorize journal entries
   750→   - Extract action items from journal → tasks
   751→   - Sentiment analysis for mood detection
   752→
   753→2. **Export Service** (from JournalCurator)
   754→   - PDF export with formatting
   755→   - JSON export (backup/migration)
   756→   - Markdown export for journal entries
   757→
   758→3. **Notifications**
   759→   - Timer completion
   760→   - Overdue task reminders
   761→   - Daily journaling prompts
   762→
   763→4. **Widgets**
   764→   - Today's tasks
   765→   - Current focus session
   766→   - Streak counter
   767→
   768→### Phase 3 (Cloud Sync)
   769→
   770→- CloudKit integration (optional)
   771→- Multi-device sync
   772→- iCloud backup of UserDefaults
   773→
   774→### Possible Migration to Core Data
   775→
   776→**When to migrate:**
   777→- User has >5000 tasks/entries
   778→- Performance degradation
   779→- Need complex queries (NSPredicate)
   780→- Relationships become complex
   781→
   782→**Migration strategy:**
   783→- Keep UserDefaults as backup
   784→- Create Core Data models matching current structs
   785→- Import existing data on first launch
   786→- Keep both systems in sync during transition
   787→
   788→## 📚 Code Style Guidelines
   789→
   790→### Naming Conventions
   791→
   792→- **Models:** `Task`, `WorkSession` (singular)
   793→- **Views:** `TasksView`, `FocusView` (plural + View suffix)
   794→- **Services:** `DataManager`, `TimerService` (Manager/Service suffix)
   795→- **Enums:** `TaskPriority`, `SessionType` (descriptive)
   796→
   797→### SwiftUI Best Practices
   798→
   799→```swift
   800→// ✅ Good: Extracted subview
   801→struct TaskRow: View {
   802→    let task: Task
   803→    var body: some View { ... }
   804→}
   805→
   806→// ❌ Bad: Inline complex views
   807→var body: some View {
   808→    List {
   809→        ForEach(tasks) { task in
   810→            HStack {
   811→                // 50 lines of UI code
   812→            }
   813→        }
   814→    }
   815→}
   816→```
   817→
   818→### Comments
   819→
   820→```swift
   821→// MARK: - Section Title (for organizing code)
   822→
   823→/// Documentation comment for public APIs
   824→/// - Parameter task: The task to update
   825→/// - Returns: Success status
   826→func updateTask(_ task: Task) -> Bool { ... }
   827→
   828→// Inline comment explaining complex logic
   829→// Calculate streak by checking consecutive days
   830→```
   831→
   832→## 🎓 Learning Resources
   833→
   834→### SwiftUI
   835→- [Apple's SwiftUI Tutorials](https://developer.apple.com/tutorials/swiftui)
   836→- [Hacking with Swift](https://www.hackingwithswift.com/quick-start/swiftui)
   837→
   838→### iOS 17+ Features
   839→- [@Observable Macro](https://developer.apple.com/documentation/observation)
   840→- [ContentUnavailableView](https://developer.apple.com/documentation/swiftui/contentunavailableview)
   841→
   842→### Architecture
   843→- [MVVM in SwiftUI](https://www.avanderlee.com/swiftui/mvvm-swiftui/)
   844→- [Singleton Pattern](https://refactoring.guru/design-patterns/singleton)
   845→
   846→## 🎨 Recent Improvements & Polish (2025-11-21)
   847→
   848→### Session 1: UX Clarity Improvements (98% Production Ready)
   849→
   850→**8 Major Improvements Implemented:**
   851→
   852→1. **Task Row Progressive Disclosure**
   853→   - Compact view shows: title, priority, 1 contextual indicator
   854→   - Tap chevron to expand for full details (notes, subtasks, tags)
   855→   - Reduces visual clutter by 50%
   856→   - File: `Features/Tasks/TasksView.swift` (TaskRow component)
   857→
   858→2. **Stats with Temporal Context**
   859→   - Added segmented time range picker: Today / This Week / All Time
   860→   - Dynamic filtering of tasks and focus sessions
   861→   - Clear label showing active timeframe
   862→   - File: `Features/Insights/InsightsView.swift`
   863→
   864→3. **Journal Metadata Reorganization**
   865→   - Changed from horizontal scroll to vertical layout
   866→   - Full-width title field at top
   867→   - Two-row grid: Category+Mood, then Favorite+Tags
   868→   - Selected tags show as dismissible chips
   869→   - File: `Features/Journal/JournalView.swift`
   870→
   871→4. **Onboarding Hints System**
   872→   - Reusable `OnboardingTip` component with icon, title, message
   873→   - `OnboardingManager` tracks shown/dismissed state via UserDefaults
   874→   - 4 contextual hints: Focus Link, Tasks Swipe, Journal Filter, Task Expand
   875→   - File: `Components/OnboardingTip.swift` (126 lines)
   876→
   877→5. **Simplified Session Type Selection**
   878→   - Primary buttons for Deep Work + Pomodoro only
   879→   - "More Options" menu for breaks and custom duration
   880→   - Reduced cognitive load for most common use cases
   881→   - File: `Features/Focus/FocusView.swift`
   882→
   883→6. **Reset Onboarding Tips (Settings)**
   884→   - Added button to reset all tips for testing/re-onboarding
   885→   - Shows confirmation alert before resetting
   886→   - File: `Features/Settings/SettingsView.swift`
   887→
   888→7. **Enhanced Empty States**
   889→   - Added action buttons: "Create Task", "Link Tasks", "Write First Entry"
   890→   - Smart detection: only show when truly empty (not filtered)
   891→   - Files: `TasksView.swift`, `FocusView.swift`, `JournalView.swift`
   892→
   893→8. **Background Timer Support**
   894→   - Timestamp-based tracking (target end date)
   895→   - Save/restore timer state via UserDefaults
   896→   - `handleAppDidBecomeActive()` and `handleAppWillResignActive()`
   897→   - Detects completion while in background
   898→   - File: `Services/TimerService.swift`
   899→
   900→### Session 2: Final Polish (100% Production Ready)
   901→
   902→**6 Final Improvements Implemented:**
   903→
   904→1. **HapticManager Optimization**
   905→   - Prepared static generator instances for 50-100ms faster response
   906→   - Added all 5 impact styles: light, medium, heavy, soft, rigid
   907→   - `prepare()` method called on app launch
   908→   - Device compatibility check (iPhone only)
   909→   - File: `HapticManager.swift` (83 lines)
   910→
   911→2. **Accessibility Labels**
   912→   - OnboardingTip dismiss: "Dismiss tip" with hint
   913→   - Time range picker: "Select time range for statistics"
   914→   - Task checkbox: Dynamic "Mark as complete/incomplete"
   915→   - Task expand: "Expand/Collapse details" with hint
   916→   - Full VoiceOver support, WCAG 2.1 Level AA compliant
   917→   - Files: `OnboardingTip.swift`, `InsightsView.swift`, `TasksView.swift`
   918→
   919→3. **Entrance Animations**
   920→   - OnboardingTip: Slide-in from top (10pt) + fade
   921→   - Spring animation: `response: 0.5, dampingFraction: 0.75`
   922→   - 100ms delay for natural appearance
   923→   - File: `Components/OnboardingTip.swift`
   924→
   925→4. **Polished Task Row Animations**
   926→   - Important star: Scale + opacity transition
   927→   - Expanded details: Asymmetric transition
   928→     - Insertion: Opacity + slide from top
   929→     - Removal: Opacity + scale (0.95)
   930→   - Consistent spring curve: `response: 0.3, dampingFraction: 0.7`
   931→   - File: `Features/Tasks/TasksView.swift`
   932→
   933→5. **Device Compatibility**
   934→   - Guard check: `UIDevice.current.userInterfaceIdiom == .phone`
   935→   - Prevents crashes on iPad/Mac Catalyst
   936→   - Graceful degradation on unsupported devices
   937→   - File: `HapticManager.swift`
   938→
   939→6. **Haptic Feedback Integration**
   940→   - Task completion: Success haptic
   941→   - Task uncomplete: Light impact
   942→   - Timer start: Light impact
   943→   - Timer pause: Medium impact
   944→   - Session added: Medium impact
   945→   - Files: `DataManager.swift`, `TimerService.swift`, `ProductivityHubApp.swift`
   946→
   947→### Key Components Added
   948→
   949→**HapticManager.swift** (83 lines)
   950→```swift
   951→enum HapticManager {
   952→    private static let mediumImpact = UIImpactFeedbackGenerator(style: .medium)
   953→    static func prepare() { /* Prepare all generators */ }
   954→    static func impact(_ style: UIImpactFeedbackGenerator.FeedbackStyle)
   955→    static func notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
   956→    static func selection()
   957→    // Convenience methods
   958→    static func taskCompleted()
   959→    static func timerStarted()
   960→    static func entryAdded()
   961→}
   962→```
   963→
   964→**OnboardingManager** (in OnboardingTip.swift)
   965→```swift
   966→@MainActor class OnboardingManager: ObservableObject {
   967→    static let shared = OnboardingManager()
   968→    @Published private(set) var hasShownFocusLinkTip: Bool
   969→    @Published private(set) var hasShownTasksSwipeTip: Bool
   970→    @Published private(set) var hasShownJournalFilterTip: Bool
   971→    @Published private(set) var hasShownTaskExpandTip: Bool
   972→    func resetAllTips()
   973→}
   974→```
   975→
   976→**FlowLayout** (in TasksView.swift)
   977→```swift
   978→struct FlowLayout: Layout {
   979→    // Custom layout for wrapping tags/chips
   980→    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ())
   981→    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ())
   982→}
   983→```
   984→
   985→### Performance Metrics
   986→
   987→- **Haptic Response Time**: 50-100ms faster (prepared generators)
   988→- **Visual Clutter Reduction**: 50% (progressive disclosure)
   989→- **Feature Discovery**: +60-70% expected (onboarding tips)
   990→- **Animation Smoothness**: Consistent 60fps (spring curves)
   991→- **Build Time**: ~30 seconds (M4 Mac)
   992→- **App Size**: ~2.5MB (no dependencies)
   993→
   994→### Session 3: CloudKit & UX Improvements (2025-11-21)
   995→
   996→**7 Improvements Implemented:**
   997→
   998→1. **CloudKitSyncService** (524 lines)
   999→   - Complete iCloud sync infrastructure
  1000→   - Upload/download for all data models (Tasks, Sessions, Journal, Tags, Templates)
  1001→   - Automatic conflict resolution (newest wins)
  1002→   - Sync status tracking (idle, syncing, success, error, offline)
  1003→   - Note: Requires Apple Developer Program ($99/year) for entitlements
  1004→   - File: `Services/CloudKitSyncService.swift`
  1005→
  1006→2. **Settings > iCloud Sync Section**
  1007→   - Toggle to enable/disable sync
  1008→   - Real-time sync status indicator
  1009→   - Last sync date display
  1010→   - Manual "Sync Now" button
  1011→   - Info about Developer Program requirement
  1012→   - File: `Features/Settings/SettingsView.swift`
  1013→
  1014→3. **Pull-to-Refresh**
  1015→   - Added to TasksView, JournalView, InsightsView
  1016→   - Reloads data from UserDefaults
  1017→   - Success haptic feedback on refresh
  1018→   - Files: `TasksView.swift`, `JournalView.swift`, `InsightsView.swift`
  1019→
  1020→4. **Debug Logs Access**
  1021→   - Added navigation link in Settings > Developer
  1022→   - Full log viewer with filtering, search, export
  1023→   - File: `Features/Settings/SettingsView.swift`
  1024→
  1025→5. **Dynamic App Version Display**
  1026→   - Shows version from CFBundleShortVersionString
  1027→   - Shows build number from CFBundleVersion
  1028→   - File: `Features/Settings/SettingsView.swift`
  1029→
  1030→6. **Bug Fixes**
  1031→   - ToastManager: Fixed auto-dismiss logic (was always true)
  1032→   - DataManager: Improved backup cascade error recovery
  1033→   - DataManager: Added duplicate initialization guard
  1034→   - ValidationService: Fixed MainActor isolation issues
  1035→
  1036→7. **Notification Permission**
  1037→   - Auto-requests on first app launch
  1038→   - Uses @AppStorage to track request status
  1039→   - File: `ProductivityHubApp.swift`
  1040→
  1041→### Session 4: Advanced Features (2025-11-21)
  1042→
  1043→**5 Features Implemented:**
  1044→
  1045→1. **Home Screen Quick Actions**
  1046→   - 4 quick actions: New Task, Start Focus, New Entry, View Insights
  1047→   - QuickActionManager for state management
  1048→   - AppDelegate + SceneDelegate for handling
  1049→   - File: `ProductivityHubApp.swift`
  1050→
  1051→2. **Keyboard Shortcuts (iPad)**
  1052→   - Cmd+1 through Cmd+5 for tab navigation
  1053→   - Hidden button pattern for keyboard capture
  1054→   - KeyboardShortcutsView component
  1055→   - File: `App/MainTabView.swift`
  1056→
  1057→3. **Spotlight Search Integration**
  1058→   - SpotlightService (210 lines) for indexing
  1059→   - Tasks and journal entries searchable in iOS Spotlight
  1060→   - Navigate to specific items from search results
  1061→   - Keywords: title, category, priority, tags, content
  1062→   - File: `Services/SpotlightService.swift`
  1063→
  1064→4. **Weekly Progress Notifications**
  1065→   - Schedule weekly summary (Sundays at 7 PM)
  1066→   - Shows: tasks completed, focus time, journal entries
  1067→   - Toggle in Settings > Notifications
  1068→   - Files: `Services/NotificationService.swift`, `Features/Settings/SettingsView.swift`
  1069→
  1070→5. **Completion Rate Trend Chart**
  1071→   - Line chart with area fill showing 7-day trends
  1072→   - Shows completion rate percentage over time
  1073→   - Average rate badge, 50% reference line
  1074→   - File: `Features/Insights/InsightsView.swift`
  1075→
  1076→6. **Daily Journal Reminder**
  1077→   - Toggle in Settings > Notifications
  1078→   - Customizable time picker (default 8 PM)
  1079→   - Prompts daily reflection on your day
  1080→   - Files: `Features/Settings/SettingsView.swift`, `Services/NotificationService.swift`
  1081→
  1082→7. **Task Due Date Reminders**
  1083→   - Automatic reminders 1 hour before task due dates
  1084→   - Toggle in Settings > Notifications (enabled by default)
  1085→   - Schedules reminders for all tasks with future due dates
  1086→   - File: `Services/NotificationService.swift`
  1087→
  1088→8. **Productivity Score**
  1089→   - Circular progress indicator (0-100 scale)
  1090→   - Score based on: Tasks (40pt), Focus (30pt), Journal (20pt), Streak (10pt)
  1091→   - Dynamic labels: Getting Started → Excellent!
  1092→   - Color-coded: Red → Orange → Blue → Green
  1093→   - Animated ring with spring animation
  1094→   - File: `Features/Insights/InsightsView.swift`
  1095→
  1096→9. **Enhanced Task Sorting**
  1097→   - 6 sort options: Priority, Due Date, Category, Created, Title, Est. Time
  1098→   - Ascending/descending toggle with animated button
  1099→   - Sort option icons for visual clarity
  1100→   - Haptic feedback on sort changes
  1101→   - File: `Features/Tasks/TasksView.swift`
  1102→
  1103→10. **Enhanced Session History**
  1104→    - Period filters: Week, Month, All Time
  1105→    - Type filters: All, Deep Work, Pomodoro, Completed
  1106→    - Stats summary: Total time, completed count, completion rate
  1107→    - Improved row design with time display
  1108→    - Swipe to delete sessions
  1109→    - File: `Features/Focus/FocusView.swift`
  1110→
  1111→11. **Journal Reading Time**
  1112→    - Estimated reading time (200 wpm average)
  1113→    - Displayed alongside word count in entry rows
  1114→    - Files: `Models/JournalEntry.swift`, `Features/Journal/JournalView.swift`
  1115→
  1116→12. **Activity Calendar (GitHub-style)**
  1117→    - 35-day contribution graph (5 weeks)
  1118→    - Activity levels based on: tasks completed, focus minutes, journal entries
  1119→    - 4-level color intensity (gray → green gradient)
  1120→    - Weekday headers (S M T W T F S)
  1121→    - Popover detail on tap showing breakdown
  1122→    - File: `Features/Insights/InsightsView.swift`
  1123→
  1124→13. **Journal Entry Sharing**
  1125→    - Swipe left to share action on journal entries
  1126→    - ShareableJournalEntry wrapper with formatted text
  1127→    - JournalShareSheet with preview, ShareLink, Copy button
  1128→    - Markdown-style formatting: title, mood, category, content
  1129→    - Haptic feedback on share action
  1130→    - File: `Features/Journal/JournalView.swift`
  1131→
  1132→14. **Task Quick Templates**
  1133→    - Bolt icon in Tasks toolbar for quick task creation
  1134→    - 6 templates: Quick Task, Work Task, Urgent Task, Health Goal, Learning Task, Creative Project
  1135→    - Pre-filled priority and category
  1136→    - Opens edit sheet for customization
  1137→    - Haptic feedback on template selection
  1138→    - File: `Features/Tasks/TasksView.swift`
  1139→
  1140→15. **Focus Session Notes Enhancement**
  1141→    - Voice input hint badge (Use dictation)
  1142→    - Quick note prompts: "Working on...", "Goal:", "Key focus:", "Blockers:"
  1143→    - One-tap prompt insertion
  1144→    - Improved layout with character count
  1145→    - File: `Features/Focus/FocusView.swift`
  1146→
  1147→16. **Journal Quick Templates**
  1148→    - Bolt icon in Journal toolbar for quick entry creation
  1149→    - 6 templates: Daily Reflection, Gratitude, Goal Setting, Idea Capture, Learning Log, Challenge
  1150→    - Pre-filled prompts with structured sections
  1151→    - Category auto-assigned based on template type
  1152→    - Opens edit sheet for customization
  1153→    - File: `Features/Journal/JournalView.swift`
  1154→
  1155→### Session 5: iPad & Mac Support (2025-11-29)
  1156→
  1157→**4 Major Features Implemented:**
  1158→
  1159→1. **Adaptive Navigation (iPad/Mac)**
  1160→   - NavigationSplitView with sidebar for iPad and Mac
  1161→   - TabView preserved for iPhone
  1162→   - `horizontalSizeClass` environment for detection
  1163→   - NavigationItem enum with icons and keyboard shortcuts
  1164→   - File: `App/MainTabView.swift`
  1165→
  1166→2. **Mac Catalyst Support**
  1167→   - Full Mac Catalyst enabled in Xcode project
  1168→   - Native macOS window controls
  1169→   - TARGETED_DEVICE_FAMILY = "1,2" (iPhone + iPad)
  1170→   - SUPPORTS_MACCATALYST = YES
  1171→   - File: `ProductivityHub-iOS.xcodeproj/project.pbxproj`
  1172→
  1173→3. **Mac Menu Bar Commands**
  1174→   - File Menu: New Task (⌘N), New Journal Entry (⇧⌘N), Start Focus (⇧⌘F)
  1175→   - View Menu: Navigation shortcuts (⌘1-4, ⌘,)
  1176→   - Uses `.commands` modifier with `#if targetEnvironment(macCatalyst)`
  1177→   - File: `ProductivityHubApp.swift`
  1178→
  1179→4. **Auto-Hide Completed Tasks**
  1180→   - Default filter changed from "All" to "Active"
  1181→   - `@AppStorage("ProductivityHub_AutoHideCompleted")` setting
  1182→   - Spring animation on task completion
  1183→   - Toggle in Settings > General
  1184→   - Files: `TasksView.swift`, `SettingsView.swift`
  1185→
  1186→5. **HapticManager Mac Compatibility**
  1187→   - Added `#if !targetEnvironment(macCatalyst)` guards
  1188→   - Prevents crashes on Mac where haptics unavailable
  1189→   - Graceful degradation on unsupported platforms
  1190→   - File: `HapticManager.swift`
  1191→
  1192→### Production Readiness Checklist
  1193→
  1194→- ✅ Core Features (Tasks, Focus, Journal, Insights, Settings)
  1195→- ✅ Data Persistence (3-layer backup system)
  1196→- ✅ Background Timer Support
  1197→- ✅ Sample Data Population
  1198→- ✅ Comprehensive Logging System
  1199→- ✅ UX Clarity (8 improvements)
  1200→- ✅ Haptic Feedback
  1201→- ✅ Accessibility Support (VoiceOver)
  1202→- ✅ Polished Animations
  1203→- ✅ Device Compatibility
  1204→- ✅ Error Handling
  1205→- ✅ Empty State Guidance
  1206→- ✅ Pull-to-Refresh
  1207→- ✅ CloudKit Sync Infrastructure (ready for paid account)
  1208→- ✅ Debug Logs Viewer
  1209→- ✅ Dynamic Version Display
  1210→- ✅ Home Screen Quick Actions
  1211→- ✅ iPad Keyboard Shortcuts
  1212→- ✅ Spotlight Search Integration
  1213→- ✅ Weekly Progress Notifications
  1214→- ✅ Completion Rate Trend Chart
  1215→- ✅ Daily Journal Reminder
  1216→- ✅ Task Due Date Reminders
  1217→- ✅ Productivity Score
  1218→- ✅ Enhanced Task Sorting (6 options + direction toggle)
  1219→- ✅ Enhanced Session History (filters + stats + swipe delete)
  1220→- ✅ Journal Reading Time Estimates
  1221→- ✅ Activity Calendar (GitHub-style contribution graph)
  1222→- ✅ Journal Entry Sharing (swipe + sheet + copy)
  1223→- ✅ Task Quick Templates (6 presets with bolt menu)
  1224→- ✅ Focus Session Notes Enhancement (voice hint + prompts)
  1225→- ✅ Journal Quick Templates (6 structured prompts)
  1226→- ✅ iPad Support (NavigationSplitView sidebar)
  1227→- ✅ Mac Catalyst Support (native macOS app)
  1228→- ✅ Mac Menu Bar Commands (⌘N, ⌘1-5, etc.)
  1229→- ✅ Auto-Hide Completed Tasks (with animation)
  1230→
  1231→**Status: 100% Production Ready for iPhone, iPad & Mac** 🚀
  1232→
  1233→## 🔗 NewsletterMaker Integration
  1234→
  1235→ProductivityHub integrates with NewsletterMaker app for cross-app productivity workflows.
  1236→
  1237→### Technical Architecture
  1238→
  1239→- **App Groups:** `group.com.neog.productivity-suite`
  1240→- **Darwin Notifications:** Real-time cross-app sync
  1241→- **URL Scheme:** `productivityhub://` (tasks, focus, journal)
  1242→
  1243→### Shared Files
  1244→
  1245→```
  1246→ProductivityHub-iOS/
  1247→├── Models/
  1248→│   └── SharedModels.swift          # SharedNewsletterIdea, SharedContact, SharedWritingSession
  1249→└── Services/
  1250→    └── SharedDataManager.swift     # Cross-app data sync service
  1251→```
  1252→
  1253→### Features
  1254→
  1255→| Feature | Description |
  1256→|---------|-------------|
  1257→| **Task → Newsletter** | Swipe left on task → "Usar em Newsletter" |
  1258→| **Journal → Newsletter** | Swipe left on entry → "Newsletter" |
  1259→| **Contact Sync** | Bidirectional sync with NewsletterMaker contacts |
  1260→| **Writing Sessions** | Receive writing session data from NewsletterMaker |
  1261→
  1262→### URL Scheme Handlers
  1263→
  1264→```
  1265→productivityhub://tasks          → Opens Tasks tab
  1266→productivityhub://focus          → Opens Focus tab
  1267→productivityhub://focus?newsletter=<id> → Opens Focus with newsletter context
  1268→productivityhub://journal        → Opens Journal tab
  1269→```
  1270→
  1271→### Related App
  1272→
  1273→- **NewsletterMaker:** `/Users/neog/NewsletterMaker/`
  1274→
  1275→## 📞 Support
  1276→
  1277→For issues or questions about this codebase:
  1278→1. Check this CLAUDE.md file first
  1279→2. Review the README.md for user-facing documentation
  1280→3. Check individual files for inline comments
  1281→4. Refer to original apps' CLAUDE.md files:
  1282→   - `/Users/neog/ToDoMax-iOS/CLAUDE.md`
  1283→   - `/Users/neog/FocusWriter/CLAUDE.md`
  1284→   - `/Users/neog/JournalCurator/CLAUDE.md`
  1285→
  1286→---
  1287→
  1288→**Last Updated:** 2025-11-29
  1289→**Version:** 1.0.0
  1290→**Status:** 100% Production Ready (iPhone, iPad & Mac - all core features + UX polish + accessibility)
  1291→**Next Phase:** App Store submission / TestFlight distribution
  1292→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

# CLAUDE.md - ProductivityHub-iOS

This file provides guidance to Claude Code (claude.ai/code) when working with this iOS app.

## 🎯 Project Overview

**ProductivityHub-iOS** is a unified productivity application that consolidates features from three separate apps:
- **ToDoMax-iOS** - Task management with subtasks and importance flags
- **FocusWriter** - Deep work timer (2 hours) + Pomodoro mode with task categories
- **JournalCurator** - AI-powered journaling with auto-categorization

**Goal:** Create a single, streamlined iOS app that eliminates redundancy and provides an intuitive productivity experience with local-first storage.

## 📊 Project Stats

- **Lines of Code:** ~2,500+ (consolidated + polish improvements)
- **Original Code:** ~8,000 lines across 3 apps
- **Code Reduction:** 70% from original 3 apps
- **Dependencies:** 0 (pure SwiftUI + Foundation + UIKit for haptics)
- **Minimum iOS:** 17.0+
- **Platforms:** iPhone, iPad, Mac Catalyst
- **Architecture:** MVVM with @Observable
- **Storage:** UserDefaults with 3-layer backup system
- **Backend:** None (local-first)
- **Production Status:** 100% Ready 🚀
- **Features:** 14 improvements across 2 polish sessions

## 🏗 Architecture

### MVVM Pattern with SwiftUI

```
ProductivityHub-iOS/
├── ProductivityHubApp.swift          # @main entry point (with haptic prep)
├── HapticManager.swift               # Optimized haptic feedback system
├── App/
│   └── MainTabView.swift             # Adaptive nav: TabView (iPhone) / NavigationSplitView (iPad/Mac)
├── Models/                           # Unified data models
│   ├── Task.swift                    # Task management (ToDoMax + FocusWriter)
│   ├── WorkSession.swift             # Focus sessions (FocusWriter)
│   ├── JournalEntry.swift            # Journal entries (JournalCurator)
│   ├── Tag.swift                     # Unified tagging system
│   └── Template.swift                # Quick capture templates
├── Services/                         # Business logic & persistence
│   ├── DataManager.swift             # Singleton with 3-layer backup + haptics
│   ├── TimerService.swift            # Deep Work + Pomodoro timer + background support
│   ├── NotificationService.swift     # Local notifications
│   └── ExportService.swift           # Data export (JSON/CSV)
├── Components/                       # Reusable UI components
│   ├── OnboardingTip.swift           # Onboarding hints system + manager
│   └── ToastView.swift               # Toast notifications
├── Features/                         # Feature-based organization
│   ├── Focus/
│   │   └── FocusView.swift           # Tab 1: Timer (with onboarding)
│   ├── Tasks/
│   │   └── TasksView.swift           # Tab 2: Task management (progressive disclosure)
│   ├── Journal/
│   │   └── JournalView.swift         # Tab 3: Journaling (vertical metadata)
│   ├── Insights/
│   │   └── InsightsView.swift        # Tab 4: Statistics (time range picker)
│   └── Settings/
│       └── SettingsView.swift        # Tab 5: Settings (reset onboarding)
└── Info.plist
```

### Key Architectural Decisions

1. **@Observable instead of @ObservableObject**
   - Using iOS 17+ `@Observable` macro for DataManager
   - Simpler syntax, automatic dependency tracking
   - More performant than `@Published` properties

2. **Singleton DataManager**
   - Single source of truth for all data
   - Shared across all views via `@EnvironmentObject`
   - Handles all CRUD operations and persistence

3. **3-Layer Backup System (from ToDoMax)**
   - Primary key: `ProductivityHub_Tasks`
   - Backup 1: `ProductivityHub_Tasks_backup1`
   - Backup 2: `ProductivityHub_Tasks_backup2`
   - Cascading recovery on data corruption

4. **Feature-Based Folder Structure**
   - Each feature (Focus, Tasks, Journal) in own folder
   - Makes navigation easier as app grows
   - Clear separation of concerns

5. **Adaptive Navigation (iPad/Mac)**
   - iPhone: TabView with 5 tabs (standard bottom bar)
   - iPad/Mac: NavigationSplitView with sidebar
   - `horizontalSizeClass` environment variable for detection
   - Seamless experience across all Apple platforms

## 💻 iPad & Mac Support

### Adaptive Navigation

The app automatically adapts its navigation pattern based on screen size:

**iPhone (Compact Width):**
```swift
TabView(selection: $quickActionManager.selectedTab) {
    FocusView().tabItem { Label("Focus", systemImage: "timer") }
    TasksView().tabItem { Label("Tasks", systemImage: "checklist") }
    // ... 5 tabs total
}
```

**iPad/Mac (Regular Width):**
```swift
NavigationSplitView {
    List(NavigationItem.allCases, selection: $selectedItem) { item in
        Label(item.rawValue, systemImage: item.icon)
    }
} detail: {
    // Content view based on selection
}
```

### Mac Menu Bar Commands

Mac Catalyst includes native menu bar commands:

| Menu | Command | Shortcut |
|------|---------|----------|
| File | New Task | ⌘N |
| File | New Journal Entry | ⇧⌘N |
| File | Start Focus Session | ⇧⌘F |
| View | Show Focus | ⌘1 |
| View | Show Tasks | ⌘2 |
| View | Show Journal | ⌘3 |
| View | Show Insights | ⌘4 |
| View | Show Settings | ⌘, |

**Implementation:** `ProductivityHubApp.swift` using `.commands` modifier with `#if targetEnvironment(macCatalyst)`.

### iPad Keyboard Shortcuts

Same shortcuts available via external keyboard on iPad:
- ⌘1 through ⌘5 for tab navigation
- Uses hidden button pattern for keyboard capture

### Platform-Specific Considerations

**Mac Catalyst:**
- Haptic feedback disabled (not supported)
- Menu bar commands enabled
- Window resizing supported
- Native macOS window controls

**iPad:**
- Sidebar navigation with split view
- Keyboard shortcuts via external keyboard
- Pointer/trackpad support

**HapticManager Compatibility:**
```swift
#if !targetEnvironment(macCatalyst)
// Haptic generators only initialized on iOS
private static let lightImpact = UIImpactFeedbackGenerator(style: .light)
#endif

static func impact(_ style: UIImpactFeedbackGenerator.FeedbackStyle) {
    #if !targetEnvironment(macCatalyst)
    guard isEnabled, supportsHaptics else { return }
    // ... haptic code
    #endif
}
```

### Building for Different Platforms

```bash
# iPhone Simulator
xcodebuild -project ProductivityHub-iOS.xcodeproj \
  -scheme ProductivityHub-iOS \
  -sdk iphonesimulator \
  -destination 'platform=iOS Simulator,name=iPhone 17 Pro'

# iPad Simulator
xcodebuild -project ProductivityHub-iOS.xcodeproj \
  -scheme ProductivityHub-iOS \
  -sdk iphonesimulator \
  -destination 'platform=iOS Simulator,name=iPad Pro 13-inch (M4)'

# Mac Catalyst
xcodebuild -project ProductivityHub-iOS.xcodeproj \
  -scheme ProductivityHub-iOS \
  -destination 'platform=macOS,variant=Mac Catalyst'
```

## 📦 Data Models

### Task (Unified from ToDoMax + FocusWriter)

```swift
struct Task: Identifiable, Codable, Hashable {
    var id: UUID
    var title: String
    var notes: String
    var isCompleted: Bool
    var isImportant: Bool                    // From ToDoMax
    var priority: TaskPriority               // From FocusWriter (low/medium/high/urgent)
    var category: TaskCategory               // From FocusWriter (8 categories)
    var subtasks: [Subtask]                  // From ToDoMax
    var linkedSessionIds: [UUID]             // Link to WorkSessions
    var tags: [UUID]                         // Link to Tags
    var estimatedDuration: TimeInterval?     // From FocusWriter
    var dueDate: Date?
    var createdAt: Date
    var completedAt: Date?
}

enum TaskPriority: String, Codable {
    case low, medium, high, urgent
}

enum TaskCategory: String, Codable {
    case work, personal, health, learning, creative, finance, social, other
}

struct Subtask: Identifiable, Codable {
    var id: UUID
    var title: String
    var isCompleted: Bool
    var createdAt: Date
}
```

**Merging Strategy:**
- ToDoMax provided: `isImportant`, `subtasks` (core task features)
- FocusWriter provided: `priority`, `category`, `estimatedDuration`, `linkedSessionIds`
- Combined: Best of both worlds - simple task management + advanced categorization

### WorkSession (from FocusWriter)

```swift
struct WorkSession: Identifiable, Codable {
    var id: UUID
    var sessionType: SessionType             // deepWork (2h) / pomodoro (25m) / break
    var duration: TimeInterval               // Actual duration
    var targetDuration: TimeInterval         // Planned duration
    var linkedTaskIds: [UUID]                // Link to Tasks
    var notes: String
    var startTime: Date
    var endTime: Date?
    var wasCompleted: Bool                   // Did they finish?
}

enum SessionType: String, Codable {
    case deepWork    // 2 hours (default)
    case pomodoro    // 25 minutes
    case break5      // 5 minutes
    case break15     // 15 minutes
}
```

**Why Keep This Model:**
- FocusWriter had excellent timer implementation
- Tracks both planned and actual time
- Links sessions to tasks for productivity insights

### JournalEntry (from JournalCurator)

```swift
struct JournalEntry: Identifiable, Codable {
    var id: UUID
    var content: String
    var title: String
    var category: EntryCategory?             // Auto-detected or manual
    var tags: [UUID]
    var linkedTaskIds: [UUID]                // Optional link to tasks
    var linkedSessionIds: [UUID]             // Optional link to sessions
    var mood: Int?                           // 1-5 scale
    var createdAt: Date
    var modifiedAt: Date
    var isFavorite: Bool
}

enum EntryCategory: String, Codable {
    case work, personal, gratitude, reflection, goal, achievement, challenge, idea, learning, other
}
```

**Why Keep This Model:**
- JournalCurator had sophisticated categorization
- Auto-detection of entry type (future AI feature)
- Mood tracking for insights
- Linking to tasks/sessions enables cross-feature insights

### Tag (Unified)

```swift
struct Tag: Identifiable, Codable {
    var id: UUID
    var name: String
    var colorHex: String                     // #007AFF format
    var icon: String?                        // SF Symbol name
    var createdAt: Date
}
```

**System Tags (Pre-populated):**
- Important, Urgent, Personal, Work, Health, Finance, Learning, Creative

**Why Unified:**
- Both JournalCurator and FocusWriter had tags
- JournalCurator's implementation was more sophisticated (colors + icons)
- Used across Tasks and JournalEntries

### Template (Quick Capture)

```swift
struct Template: Identifiable, Codable {
    var id: UUID
    var name: String
    var type: TemplateType                   // task / journal / both
    var icon: String

    // Task template fields
    var taskTitle: String?
    var taskPriority: TaskPriority?
    var taskCategory: TaskCategory?

    // Journal template fields
    var journalPrompt: String?
    var journalCategory: EntryCategory?

    var defaultTags: [UUID]
    var usageCount: Int
}

enum TemplateType: String, Codable {
    case task, journal, both
}
```

**System Templates (Pre-populated):**
- Daily Review (journal)
- Quick Task (task)
- Work Task (task)
- Gratitude Entry (journal)
- Goal + Task (both)

**Why Added:**
- Reduces friction for common actions
- Inspired by JournalCurator's prompts
- Extends to tasks as well

## 🗄 Data Persistence

### 3-Layer Backup System (from ToDoMax)

**Strategy:**
```
Save Operation:
1. Validate new data can be decoded (integrity check)
2. Cascade existing backups: current → backup1, backup1 → backup2
3. Save new data to current key
4. Log operation

Load Operation:
1. Try primary key → Success? Return
2. Try backup1 key → Success? Restore to primary, return
3. Try backup2 key → Success? Restore to primary + backup1, return
4. No data found → Return default value
```

**UserDefaults Keys:**
```swift
// Tasks
"ProductivityHub_Tasks"
"ProductivityHub_Tasks_backup1"
"ProductivityHub_Tasks_backup2"

// WorkSessions
"ProductivityHub_Sessions"
"ProductivityHub_Sessions_backup1"
"ProductivityHub_Sessions_backup2"

// Journal Entries
"ProductivityHub_Journal"
"ProductivityHub_Journal_backup1"
"ProductivityHub_Journal_backup2"

// Tags
"ProductivityHub_Tags"
"ProductivityHub_Tags_backup1"
"ProductivityHub_Tags_backup2"

// Templates
"ProductivityHub_Templates"
"ProductivityHub_Templates_backup1"
"ProductivityHub_Templates_backup2"
```

**Why UserDefaults Instead of Core Data?**
- Simpler implementation (no migration hassles)
- Faster for small-to-medium datasets (<10MB)
- User chose "Sem Backend" (no backend)
- ToDoMax's backup system proven reliable
- Can migrate to Core Data later if needed

**Data Validation:**
```swift
// Before saving, verify data can be decoded
guard let encoded = try? JSONEncoder().encode(data) else { return }
guard (try? JSONDecoder().decode(type(of: data).self, from: encoded)) != nil else { return }
```

## 🎨 UI/UX Design

### TabView Navigation (5 Tabs)

1. **Focus** (Timer icon)
   - Large timer display (2h default, 25m Pomodoro)
   - Session type selector
   - Start/Pause/Stop controls
   - Quick task link
   - Session history

2. **Tasks** (Checklist icon)
   - List with checkboxes
   - Filter: All / Active / Completed / Important
   - Sort: Priority / Due Date / Category
   - Subtask progress indicators
   - Swipe actions: Edit / Delete / Important

3. **Journal** (Book icon)
   - Chronological list (newest first)
   - Entry cards with excerpts
   - Category/mood indicators
   - Search functionality
   - Filter by category/tags

4. **Insights** (Chart icon)
   - Current streak (days)
   - Task statistics (completed/pending/overdue)
   - Total focus time (hours)
   - Today's activity summary
   - Charts: Category breakdown, completion trends

5. **Settings** (Gear icon)
   - Tag management
   - Template management
   - Export data (JSON/CSV)
   - About section
   - Clear all data (danger zone)

### Color Scheme

**System Colors (iOS native):**
- Primary: `.blue` (iOS system blue)
- Success: `.green` (completed items)
- Warning: `.orange` (overdue)
- Danger: `.red` (urgent)
- Secondary: `.gray` (low priority)

**Priority Colors:**
- Low: Gray
- Medium: Blue
- High: Orange
- Urgent: Red

**Category Colors:**
- Work: Blue
- Personal: Purple
- Health: Pink
- Learning: Teal
- Creative: Orange
- Finance: Green
- Social: Indigo
- Other: Gray

## 🔧 Key Services

### DataManager (Singleton)

**Responsibilities:**
- Load all data on app launch
- Save all data when app goes to background
- Provide CRUD operations for all models
- Calculate statistics (streak, completion rate, etc.)
- Handle 3-layer backup system

**Usage:**
```swift
@EnvironmentObject var dataManager: DataManager

// Add task
dataManager.addTask(newTask)

// Update task
dataManager.updateTask(modifiedTask)

// Toggle completion
dataManager.toggleTaskCompletion(task)

// Get statistics
let stats = dataManager.getTaskStatistics()
let streak = dataManager.getStreakDays()
let todayFocus = dataManager.getTotalFocusTime()
```

### TimerService (@Observable)

**Responsibilities:**
- Manage timer state (running/paused)
- Track elapsed time
- Handle Deep Work (2h) and Pomodoro (25m) modes
- Auto-stop when target reached
- Create WorkSession records

**Usage:**
```swift
@StateObject private var timerService = TimerService()

// Start 2-hour deep work session
timerService.startTimer(type: .deepWork)

// Start 25-minute Pomodoro
timerService.startTimer(type: .pomodoro)

// Pause/Resume
timerService.pauseTimer()
timerService.resumeTimer()

// Stop and save
timerService.stopTimer(save: true)
if let session = timerService.currentSession {
    dataManager.addWorkSession(session)
}
```

## 🚀 Development Workflow

### Building the Project

```bash
# Generate Xcode project (first time)
cd /Users/neog/ProductivityHub-iOS
ruby generate-xcode-project.rb

# Open in Xcode
open ProductivityHub-iOS.xcodeproj

# Or build from command line
xcodebuild -project ProductivityHub-iOS.xcodeproj \
  -scheme ProductivityHub-iOS \
  -sdk iphonesimulator \
  -destination 'platform=iOS Simulator,name=iPhone 15 Pro'
```

### Testing on Simulator

```bash
# List available simulators
xcrun simctl list devices

# Boot simulator
xcrun simctl boot <DEVICE_ID>

# Install app
xcrun simctl install <DEVICE_ID> <PATH_TO_APP>

# Launch app
xcrun simctl launch <DEVICE_ID> com.yourname.ProductivityHub-iOS

# View logs
xcrun simctl spawn <DEVICE_ID> log stream --predicate 'process == "ProductivityHub-iOS"'
```

### Adding New Features

**Example: Adding a new Task property**

1. Update `Task.swift` model:
```swift
struct Task {
    // ... existing properties
    var newProperty: String = "default"
}
```

2. No migration needed (Codable handles it)
3. If old data doesn't have property, defaults will be used
4. Update UI to display/edit new property

**Example: Adding a new View**

1. Create new Swift file in appropriate feature folder
2. Import SwiftUI and add to project
3. Add `@EnvironmentObject var dataManager: DataManager` if needed
4. Use `#Preview` for quick testing

## 📋 Common Tasks

### Reading Data from DataManager

```swift
struct MyView: View {
    @EnvironmentObject var dataManager: DataManager

    var body: some View {
        List(dataManager.tasks) { task in
            Text(task.title)
        }
    }
}
```

### Creating a Task

```swift
Button("Add Task") {
    let newTask = Task(
        title: "New Task",
        priority: .medium,
        category: .personal
    )
    dataManager.addTask(newTask)
}
```

### Filtering Tasks

```swift
// All incomplete tasks
let activeTasks = dataManager.tasks.filter { !$0.isCompleted }

// Important tasks
let importantTasks = dataManager.tasks.filter { $0.isImportant }

// Overdue tasks
let overdueTasks = dataManager.tasks.filter { $0.isOverdue }

// Tasks by category
let workTasks = dataManager.tasks.filter { $0.category == .work }
```

### Displaying Statistics

```swift
let stats = dataManager.getTaskStatistics()

Text("Completion Rate: \(Int(stats.completionRate))%")
Text("Completed: \(stats.completed) / \(stats.total)")
Text("Pending: \(stats.pending)")
Text("Overdue: \(stats.overdue)")
```

## 🐛 Common Issues & Solutions

### Issue: App crashes on launch

**Cause:** Corrupted data in UserDefaults

**Solution:**
```swift
// In DataManager, add recovery logic
if tasks.isEmpty && workSessions.isEmpty && journalEntries.isEmpty {
    print("⚠ All data empty - possible corruption")
    // Try manual recovery or reset
}
```

**Nuclear option:**
```bash
# Clear all UserDefaults for app (simulator)
xcrun simctl spawn booted defaults delete com.yourname.ProductivityHub-iOS
```

### Issue: Timer doesn't stop automatically

**Cause:** Timer not invalidated properly

**Solution:**
```swift
func stopTimer() {
    timer?.invalidate()
    timer = nil  // Important: release reference
    isRunning = false
}
```

### Issue: Data not saving when app goes to background

**Cause:** `onReceive` not triggered

**Solution:**
```swift
// In ProductivityHubApp.swift
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
    dataManager.saveAllData()
}

// Also save when app terminates
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification)) { _ in
    dataManager.saveAllData()
}
```

### Issue: Xcode project out of sync with files

**Cause:** Added/removed files manually

**Solution:**
```bash
# Regenerate project
ruby generate-xcode-project.rb
# Xcode will ask to reload - click "Reload"
```

## 📊 Performance Considerations

### UserDefaults Limits

- **Practical limit:** 5-10MB recommended
- **Hard limit:** ~40MB (iOS may purge)
- **Our usage:** ~1-5MB typical (thousands of items)

**Monitoring:**
```swift
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(tasks) {
    let sizeInMB = Double(encoded.count) / 1_048_576
    print("Tasks size: \(sizeInMB) MB")
}
```

### Memory Optimization

- Use `[weak self]` in Timer closures
- Invalidate timers when not needed
- Avoid loading all journal entries at once (pagination if >1000)

### UI Performance

- Use `List` instead of `ScrollView` + `ForEach` for large lists
- Lazy loading with `.onAppear` for expensive operations
- Debounce search queries

## 🔮 Future Enhancements

### Phase 2 (Advanced Features)

1. **AI Content Parser** (from JournalCurator)
   - Auto-categorize journal entries
   - Extract action items from journal → tasks
   - Sentiment analysis for mood detection

2. **Export Service** (from JournalCurator)
   - PDF export with formatting
   - JSON export (backup/migration)
   - Markdown export for journal entries

3. **Notifications**
   - Timer completion
   - Overdue task reminders
   - Daily journaling prompts

4. **Widgets**
   - Today's tasks
   - Current focus session
   - Streak counter

### Phase 3 (Cloud Sync)

- CloudKit integration (optional)
- Multi-device sync
- iCloud backup of UserDefaults

### Possible Migration to Core Data

**When to migrate:**
- User has >5000 tasks/entries
- Performance degradation
- Need complex queries (NSPredicate)
- Relationships become complex

**Migration strategy:**
- Keep UserDefaults as backup
- Create Core Data models matching current structs
- Import existing data on first launch
- Keep both systems in sync during transition

## 📚 Code Style Guidelines

### Naming Conventions

- **Models:** `Task`, `WorkSession` (singular)
- **Views:** `TasksView`, `FocusView` (plural + View suffix)
- **Services:** `DataManager`, `TimerService` (Manager/Service suffix)
- **Enums:** `TaskPriority`, `SessionType` (descriptive)

### SwiftUI Best Practices

```swift
// ✅ Good: Extracted subview
struct TaskRow: View {
    let task: Task
    var body: some View { ... }
}

// ❌ Bad: Inline complex views
var body: some View {
    List {
        ForEach(tasks) { task in
            HStack {
                // 50 lines of UI code
            }
        }
    }
}
```

### Comments

```swift
// MARK: - Section Title (for organizing code)

/// Documentation comment for public APIs
/// - Parameter task: The task to update
/// - Returns: Success status
func updateTask(_ task: Task) -> Bool { ... }

// Inline comment explaining complex logic
// Calculate streak by checking consecutive days
```

## 🎓 Learning Resources

### SwiftUI
- [Apple's SwiftUI Tutorials](https://developer.apple.com/tutorials/swiftui)
- [Hacking with Swift](https://www.hackingwithswift.com/quick-start/swiftui)

### iOS 17+ Features
- [@Observable Macro](https://developer.apple.com/documentation/observation)
- [ContentUnavailableView](https://developer.apple.com/documentation/swiftui/contentunavailableview)

### Architecture
- [MVVM in SwiftUI](https://www.avanderlee.com/swiftui/mvvm-swiftui/)
- [Singleton Pattern](https://refactoring.guru/design-patterns/singleton)

## 🎨 Recent Improvements & Polish (2025-11-21)

### Session 1: UX Clarity Improvements (98% Production Ready)

**8 Major Improvements Implemented:**

1. **Task Row Progressive Disclosure**
   - Compact view shows: title, priority, 1 contextual indicator
   - Tap chevron to expand for full details (notes, subtasks, tags)
   - Reduces visual clutter by 50%
   - File: `Features/Tasks/TasksView.swift` (TaskRow component)

2. **Stats with Temporal Context**
   - Added segmented time range picker: Today / This Week / All Time
   - Dynamic filtering of tasks and focus sessions
   - Clear label showing active timeframe
   - File: `Features/Insights/InsightsView.swift`

3. **Journal Metadata Reorganization**
   - Changed from horizontal scroll to vertical layout
   - Full-width title field at top
   - Two-row grid: Category+Mood, then Favorite+Tags
   - Selected tags show as dismissible chips
   - File: `Features/Journal/JournalView.swift`

4. **Onboarding Hints System**
   - Reusable `OnboardingTip` component with icon, title, message
   - `OnboardingManager` tracks shown/dismissed state via UserDefaults
   - 4 contextual hints: Focus Link, Tasks Swipe, Journal Filter, Task Expand
   - File: `Components/OnboardingTip.swift` (126 lines)

5. **Simplified Session Type Selection**
   - Primary buttons for Deep Work + Pomodoro only
   - "More Options" menu for breaks and custom duration
   - Reduced cognitive load for most common use cases
   - File: `Features/Focus/FocusView.swift`

6. **Reset Onboarding Tips (Settings)**
   - Added button to reset all tips for testing/re-onboarding
   - Shows confirmation alert before resetting
   - File: `Features/Settings/SettingsView.swift`

7. **Enhanced Empty States**
   - Added action buttons: "Create Task", "Link Tasks", "Write First Entry"
   - Smart detection: only show when truly empty (not filtered)
   - Files: `TasksView.swift`, `FocusView.swift`, `JournalView.swift`

8. **Background Timer Support**
   - Timestamp-based tracking (target end date)
   - Save/restore timer state via UserDefaults
   - `handleAppDidBecomeActive()` and `handleAppWillResignActive()`
   - Detects completion while in background
   - File: `Services/TimerService.swift`

### Session 2: Final Polish (100% Production Ready)

**6 Final Improvements Implemented:**

1. **HapticManager Optimization**
   - Prepared static generator instances for 50-100ms faster response
   - Added all 5 impact styles: light, medium, heavy, soft, rigid
   - `prepare()` method called on app launch
   - Device compatibility check (iPhone only)
   - File: `HapticManager.swift` (83 lines)

2. **Accessibility Labels**
   - OnboardingTip dismiss: "Dismiss tip" with hint
   - Time range picker: "Select time range for statistics"
   - Task checkbox: Dynamic "Mark as complete/incomplete"
   - Task expand: "Expand/Collapse details" with hint
   - Full VoiceOver support, WCAG 2.1 Level AA compliant
   - Files: `OnboardingTip.swift`, `InsightsView.swift`, `TasksView.swift`

3. **Entrance Animations**
   - OnboardingTip: Slide-in from top (10pt) + fade
   - Spring animation: `response: 0.5, dampingFraction: 0.75`
   - 100ms delay for natural appearance
   - File: `Components/OnboardingTip.swift`

4. **Polished Task Row Animations**
   - Important star: Scale + opacity transition
   - Expanded details: Asymmetric transition
     - Insertion: Opacity + slide from top
     - Removal: Opacity + scale (0.95)
   - Consistent spring curve: `response: 0.3, dampingFraction: 0.7`
   - File: `Features/Tasks/TasksView.swift`

5. **Device Compatibility**
   - Guard check: `UIDevice.current.userInterfaceIdiom == .phone`
   - Prevents crashes on iPad/Mac Catalyst
   - Graceful degradation on unsupported devices
   - File: `HapticManager.swift`

6. **Haptic Feedback Integration**
   - Task completion: Success haptic
   - Task uncomplete: Light impact
   - Timer start: Light impact
   - Timer pause: Medium impact
   - Session added: Medium impact
   - Files: `DataManager.swift`, `TimerService.swift`, `ProductivityHubApp.swift`

### Key Components Added

**HapticManager.swift** (83 lines)
```swift
enum HapticManager {
    private static let mediumImpact = UIImpactFeedbackGenerator(style: .medium)
    static func prepare() { /* Prepare all generators */ }
    static func impact(_ style: UIImpactFeedbackGenerator.FeedbackStyle)
    static func notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
    static func selection()
    // Convenience methods
    static func taskCompleted()
    static func timerStarted()
    static func entryAdded()
}
```

**OnboardingManager** (in OnboardingTip.swift)
```swift
@MainActor class OnboardingManager: ObservableObject {
    static let shared = OnboardingManager()
    @Published private(set) var hasShownFocusLinkTip: Bool
    @Published private(set) var hasShownTasksSwipeTip: Bool
    @Published private(set) var hasShownJournalFilterTip: Bool
    @Published private(set) var hasShownTaskExpandTip: Bool
    func resetAllTips()
}
```

**FlowLayout** (in TasksView.swift)
```swift
struct FlowLayout: Layout {
    // Custom layout for wrapping tags/chips
    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ())
    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ())
}
```

### Performance Metrics

- **Haptic Response Time**: 50-100ms faster (prepared generators)
- **Visual Clutter Reduction**: 50% (progressive disclosure)
- **Feature Discovery**: +60-70% expected (onboarding tips)
- **Animation Smoothness**: Consistent 60fps (spring curves)
- **Build Time**: ~30 seconds (M4 Mac)
- **App Size**: ~2.5MB (no dependencies)

### Session 3: CloudKit & UX Improvements (2025-11-21)

**7 Improvements Implemented:**

1. **CloudKitSyncService** (524 lines)
   - Complete iCloud sync infrastructure
   - Upload/download for all data models (Tasks, Sessions, Journal, Tags, Templates)
   - Automatic conflict resolution (newest wins)
   - Sync status tracking (idle, syncing, success, error, offline)
   - Note: Requires Apple Developer Program ($99/year) for entitlements
   - File: `Services/CloudKitSyncService.swift`

2. **Settings > iCloud Sync Section**
   - Toggle to enable/disable sync
   - Real-time sync status indicator
   - Last sync date display
   - Manual "Sync Now" button
   - Info about Developer Program requirement
   - File: `Features/Settings/SettingsView.swift`

3. **Pull-to-Refresh**
   - Added to TasksView, JournalView, InsightsView
   - Reloads data from UserDefaults
   - Success haptic feedback on refresh
   - Files: `TasksView.swift`, `JournalView.swift`, `InsightsView.swift`

4. **Debug Logs Access**
   - Added navigation link in Settings > Developer
   - Full log viewer with filtering, search, export
   - File: `Features/Settings/SettingsView.swift`

5. **Dynamic App Version Display**
   - Shows version from CFBundleShortVersionString
   - Shows build number from CFBundleVersion
   - File: `Features/Settings/SettingsView.swift`

6. **Bug Fixes**
   - ToastManager: Fixed auto-dismiss logic (was always true)
   - DataManager: Improved backup cascade error recovery
   - DataManager: Added duplicate initialization guard
   - ValidationService: Fixed MainActor isolation issues

7. **Notification Permission**
   - Auto-requests on first app launch
   - Uses @AppStorage to track request status
   - File: `ProductivityHubApp.swift`

### Session 4: Advanced Features (2025-11-21)

**5 Features Implemented:**

1. **Home Screen Quick Actions**
   - 4 quick actions: New Task, Start Focus, New Entry, View Insights
   - QuickActionManager for state management
   - AppDelegate + SceneDelegate for handling
   - File: `ProductivityHubApp.swift`

2. **Keyboard Shortcuts (iPad)**
   - Cmd+1 through Cmd+5 for tab navigation
   - Hidden button pattern for keyboard capture
   - KeyboardShortcutsView component
   - File: `App/MainTabView.swift`

3. **Spotlight Search Integration**
   - SpotlightService (210 lines) for indexing
   - Tasks and journal entries searchable in iOS Spotlight
   - Navigate to specific items from search results
   - Keywords: title, category, priority, tags, content
   - File: `Services/SpotlightService.swift`

4. **Weekly Progress Notifications**
   - Schedule weekly summary (Sundays at 7 PM)
   - Shows: tasks completed, focus time, journal entries
   - Toggle in Settings > Notifications
   - Files: `Services/NotificationService.swift`, `Features/Settings/SettingsView.swift`

5. **Completion Rate Trend Chart**
   - Line chart with area fill showing 7-day trends
   - Shows completion rate percentage over time
   - Average rate badge, 50% reference line
   - File: `Features/Insights/InsightsView.swift`

6. **Daily Journal Reminder**
   - Toggle in Settings > Notifications
   - Customizable time picker (default 8 PM)
   - Prompts daily reflection on your day
   - Files: `Features/Settings/SettingsView.swift`, `Services/NotificationService.swift`

7. **Task Due Date Reminders**
   - Automatic reminders 1 hour before task due dates
   - Toggle in Settings > Notifications (enabled by default)
   - Schedules reminders for all tasks with future due dates
   - File: `Services/NotificationService.swift`

8. **Productivity Score**
   - Circular progress indicator (0-100 scale)
   - Score based on: Tasks (40pt), Focus (30pt), Journal (20pt), Streak (10pt)
   - Dynamic labels: Getting Started → Excellent!
   - Color-coded: Red → Orange → Blue → Green
   - Animated ring with spring animation
   - File: `Features/Insights/InsightsView.swift`

9. **Enhanced Task Sorting**
   - 6 sort options: Priority, Due Date, Category, Created, Title, Est. Time
   - Ascending/descending toggle with animated button
   - Sort option icons for visual clarity
   - Haptic feedback on sort changes
   - File: `Features/Tasks/TasksView.swift`

10. **Enhanced Session History**
    - Period filters: Week, Month, All Time
    - Type filters: All, Deep Work, Pomodoro, Completed
    - Stats summary: Total time, completed count, completion rate
    - Improved row design with time display
    - Swipe to delete sessions
    - File: `Features/Focus/FocusView.swift`

11. **Journal Reading Time**
    - Estimated reading time (200 wpm average)
    - Displayed alongside word count in entry rows
    - Files: `Models/JournalEntry.swift`, `Features/Journal/JournalView.swift`

12. **Activity Calendar (GitHub-style)**
    - 35-day contribution graph (5 weeks)
    - Activity levels based on: tasks completed, focus minutes, journal entries
    - 4-level color intensity (gray → green gradient)
    - Weekday headers (S M T W T F S)
    - Popover detail on tap showing breakdown
    - File: `Features/Insights/InsightsView.swift`

13. **Journal Entry Sharing**
    - Swipe left to share action on journal entries
    - ShareableJournalEntry wrapper with formatted text
    - JournalShareSheet with preview, ShareLink, Copy button
    - Markdown-style formatting: title, mood, category, content
    - Haptic feedback on share action
    - File: `Features/Journal/JournalView.swift`

14. **Task Quick Templates**
    - Bolt icon in Tasks toolbar for quick task creation
    - 6 templates: Quick Task, Work Task, Urgent Task, Health Goal, Learning Task, Creative Project
    - Pre-filled priority and category
    - Opens edit sheet for customization
    - Haptic feedback on template selection
    - File: `Features/Tasks/TasksView.swift`

15. **Focus Session Notes Enhancement**
    - Voice input hint badge (Use dictation)
    - Quick note prompts: "Working on...", "Goal:", "Key focus:", "Blockers:"
    - One-tap prompt insertion
    - Improved layout with character count
    - File: `Features/Focus/FocusView.swift`

16. **Journal Quick Templates**
    - Bolt icon in Journal toolbar for quick entry creation
    - 6 templates: Daily Reflection, Gratitude, Goal Setting, Idea Capture, Learning Log, Challenge
    - Pre-filled prompts with structured sections
    - Category auto-assigned based on template type
    - Opens edit sheet for customization
    - File: `Features/Journal/JournalView.swift`

### Session 5: iPad & Mac Support (2025-11-29)

**4 Major Features Implemented:**

1. **Adaptive Navigation (iPad/Mac)**
   - NavigationSplitView with sidebar for iPad and Mac
   - TabView preserved for iPhone
   - `horizontalSizeClass` environment for detection
   - NavigationItem enum with icons and keyboard shortcuts
   - File: `App/MainTabView.swift`

2. **Mac Catalyst Support**
   - Full Mac Catalyst enabled in Xcode project
   - Native macOS window controls
   - TARGETED_DEVICE_FAMILY = "1,2" (iPhone + iPad)
   - SUPPORTS_MACCATALYST = YES
   - File: `ProductivityHub-iOS.xcodeproj/project.pbxproj`

3. **Mac Menu Bar Commands**
   - File Menu: New Task (⌘N), New Journal Entry (⇧⌘N), Start Focus (⇧⌘F)
   - View Menu: Navigation shortcuts (⌘1-4, ⌘,)
   - Uses `.commands` modifier with `#if targetEnvironment(macCatalyst)`
   - File: `ProductivityHubApp.swift`

4. **Auto-Hide Completed Tasks**
   - Default filter changed from "All" to "Active"
   - `@AppStorage("ProductivityHub_AutoHideCompleted")` setting
   - Spring animation on task completion
   - Toggle in Settings > General
   - Files: `TasksView.swift`, `SettingsView.swift`

5. **HapticManager Mac Compatibility**
   - Added `#if !targetEnvironment(macCatalyst)` guards
   - Prevents crashes on Mac where haptics unavailable
   - Graceful degradation on unsupported platforms
   - File: `HapticManager.swift`

### Production Readiness Checklist

- ✅ Core Features (Tasks, Focus, Journal, Insights, Settings)
- ✅ Data Persistence (3-layer backup system)
- ✅ Background Timer Support
- ✅ Sample Data Population
- ✅ Comprehensive Logging System
- ✅ UX Clarity (8 improvements)
- ✅ Haptic Feedback
- ✅ Accessibility Support (VoiceOver)
- ✅ Polished Animations
- ✅ Device Compatibility
- ✅ Error Handling
- ✅ Empty State Guidance
- ✅ Pull-to-Refresh
- ✅ CloudKit Sync Infrastructure (ready for paid account)
- ✅ Debug Logs Viewer
- ✅ Dynamic Version Display
- ✅ Home Screen Quick Actions
- ✅ iPad Keyboard Shortcuts
- ✅ Spotlight Search Integration
- ✅ Weekly Progress Notifications
- ✅ Completion Rate Trend Chart
- ✅ Daily Journal Reminder
- ✅ Task Due Date Reminders
- ✅ Productivity Score
- ✅ Enhanced Task Sorting (6 options + direction toggle)
- ✅ Enhanced Session History (filters + stats + swipe delete)
- ✅ Journal Reading Time Estimates
- ✅ Activity Calendar (GitHub-style contribution graph)
- ✅ Journal Entry Sharing (swipe + sheet + copy)
- ✅ Task Quick Templates (6 presets with bolt menu)
- ✅ Focus Session Notes Enhancement (voice hint + prompts)
- ✅ Journal Quick Templates (6 structured prompts)
- ✅ iPad Support (NavigationSplitView sidebar)
- ✅ Mac Catalyst Support (native macOS app)
- ✅ Mac Menu Bar Commands (⌘N, ⌘1-5, etc.)
- ✅ Auto-Hide Completed Tasks (with animation)

**Status: 100% Production Ready for iPhone, iPad & Mac** 🚀

## 🔗 NewsletterMaker Integration

ProductivityHub integrates with NewsletterMaker app for cross-app productivity workflows.

### Technical Architecture

- **App Groups:** `group.com.neog.productivity-suite`
- **Darwin Notifications:** Real-time cross-app sync
- **URL Scheme:** `productivityhub://` (tasks, focus, journal)

### Shared Files

```
ProductivityHub-iOS/
├── Models/
│   └── SharedModels.swift          # SharedNewsletterIdea, SharedContact, SharedWritingSession
└── Services/
    └── SharedDataManager.swift     # Cross-app data sync service
```

### Features

| Feature | Description |
|---------|-------------|
| **Task → Newsletter** | Swipe left on task → "Usar em Newsletter" |
| **Journal → Newsletter** | Swipe left on entry → "Newsletter" |
| **Contact Sync** | Bidirectional sync with NewsletterMaker contacts |
| **Writing Sessions** | Receive writing session data from NewsletterMaker |

### URL Scheme Handlers

```
productivityhub://tasks          → Opens Tasks tab
productivityhub://focus          → Opens Focus tab
productivityhub://focus?newsletter=<id> → Opens Focus with newsletter context
productivityhub://journal        → Opens Journal tab
```

### Related App

- **NewsletterMaker:** `/Users/neog/NewsletterMaker/`

## 📞 Support

For issues or questions about this codebase:
1. Check this CLAUDE.md file first
2. Review the README.md for user-facing documentation
3. Check individual files for inline comments
4. Refer to original apps' CLAUDE.md files:
   - `/Users/neog/ToDoMax-iOS/CLAUDE.md`
   - `/Users/neog/FocusWriter/CLAUDE.md`
   - `/Users/neog/JournalCurator/CLAUDE.md`

---

**Last Updated:** 2025-11-29
**Version:** 1.0.0
**Status:** 100% Production Ready (iPhone, iPad & Mac - all core features + UX polish + accessibility)
**Next Phase:** App Store submission / TestFlight distribution


Excellent! Now let me explore the actual source code structure of these apps to understand the implementation patterns:


Bash

find /Users/neog/Apps/iOS/PROD-ProductivityHub -name "*.swift" -type f | head -30

List Swift source files in ProductivityHub


find /Users/neog/Apps/iOS/PROD-96Blocks -name "*.swift" -type f 2>/dev/null | head -20

List Swift source files in 96Blocks


Check ProductivityHub directory contents


total 936
drwxr-xr-x@ 61 neog  staff   1952 Dec 21 20:52 .
drwxr-xr-x@ 38 neog  staff   1216 Dec 23 06:52 ..
-rw-r--r--@  1 neog  staff   9326 Nov 21 13:32 APP-STORE-SUBMISSION-GUIDE.md
-rw-r--r--@  1 neog  staff  11292 Nov 19 18:17 AnalyticsService.swift
drwxr-xr-x@  3 neog  staff     96 Dec  2 16:32 App
-rw-r--r--@  1 neog  staff   5601 Nov 19 18:16 AppearanceSettingsView.swift
drwxr-xr-x@  3 neog  staff     96 Nov 20 15:34 Assets.xcassets
-rw-------@  1 neog  staff  40004 Nov 29 19:02 CLAUDE.md
-rw-------@  1 neog  staff   3249 Nov 17 14:21 COMANDOS-TERMINAL.sh
-rw-r--r--@  1 neog  staff   2853 Nov 17 11:31 COMO-INICIAR.md
-rw-r--r--@  1 neog  staff  12405 Nov 19 03:54 COMPLETION_SUMMARY.md
-rw-------@  1 neog  staff   6452 Nov 17 14:21 COPIE-E-COLE.txt
-rw-------@  1 neog  staff   3415 Nov 17 13:13 CREATE-XCODE-PROJECT.sh
drwxr-xr-x@  4 neog  staff    128 Nov 21 16:22 Components
-rw-r--r--@  1 neog  staff   8745 Nov 19 03:58 DOCUMENTATION_INDEX.md
-rw-r--r--@  1 neog  staff   8971 Nov 17 11:49 EXECUCAO-COMPLETA.md
-rw-------@  1 neog  staff   4902 Nov 17 14:12 EXECUTE-NOW.md
drwxr-xr-x@  4 neog  staff    128 Nov 22 18:55 Extensions
-rw-r--r--@  1 neog  staff  12623 Nov 19 03:57 FEATURE_SHOWCASE.md
drwxr-xr-x@  7 neog  staff    224 Dec  2 18:37 Features
-rw-r--r--@  1 neog  staff   4223 Nov 29 15:35 HapticManager.swift
-rw-------@  1 neog  staff   2269 Nov 29 17:56 Info.plist
drwxr-xr-x@  8 neog  staff    256 Nov 29 17:25 Models
-rw-r--r--@  1 neog  staff   7400 Nov 21 13:27 PRODUCTION-READY-REPORT.md
-rw-------@  1 neog  staff  12325 Nov 17 11:13 PROJECT-SUMMARY.md
-rw-r--r--@  1 neog  staff   9401 Nov 19 00:12 PROJECT_STATUS.md
-rw-------@  1 neog  staff    544 Nov 29 17:24 ProductivityHub-iOS.entitlements
drwxr-xr-x@  5 neog  staff    160 Dec  2 16:01 ProductivityHub-iOS.xcodeproj
drwxr-xr-x@  6 neog  staff    192 Dec  2 18:37 ProductivityHub-iOS.xcodeproj.backup
-rw-------@  1 neog  staff  16027 Dec  2 15:48 ProductivityHubApp.swift
-rwxr-xr-x@  1 neog  staff   2138 Nov 21 13:44 QUICK-COMMANDS.sh
-rw-------@  1 neog  staff   9128 Nov 19 00:00 README.md
drwxr-xr-x@  2 neog  staff     64 Nov 17 11:05 Resources
-rw-------@  1 neog  staff   5037 Nov 17 13:13 STATUS.md
drwxr-xr-x@ 10 neog  staff    320 Dec  2 16:30 Services
-rw-r--r--@  1 neog  staff  10958 Nov 21 13:31 TESTING-CHECKLIST.md
-rw-------@  1 neog  staff  13750 Nov 20 16:51 TESTING-STATUS.md
-rw-r--r--@  1 neog  staff   7147 Nov 19 18:17 TimerSettingsView.swift
-rw-r--r--@  1 neog  staff   4769 Nov 21 16:40 ValidationService.swift
-rw-r--r--@  1 neog  staff   3117 Nov 17 11:56 add-files-to-pbxproj.rb
-rwx--x--x@  1 neog  staff   2483 Nov 17 11:36 add-files-to-xcode.sh
-rw-------@  1 neog  staff   4099 Nov 20 17:33 add-logging-files.rb
-rw-r--r--@  1 neog  staff  26209 Nov 20 17:33 build.log
-rw-r--r--@  1 neog  staff   3241 Nov 17 12:20 clean-pbxproj.rb
-rw-------@  1 neog  staff   2136 Nov 17 14:12 create-project.rb
-rwxr-xr-x@  1 neog  staff   2322 Nov 19 03:55 demo-app.sh
-rw-------@  1 neog  staff    867 Nov 17 11:51 fix-xcode-project.rb
-rw-------@  1 neog  staff   3826 Nov 20 15:34 generate-app-icon.py
-rwx--x--x@  1 neog  staff  15880 Nov 22 18:53 generate-xcode-project.rb
-rw-------@  1 neog  staff   1158 Nov 17 11:21 project.yml
-rw-r--r--@  1 neog  staff   2109 Nov 17 12:24 rebuild-pbxproj.rb
-rwx--x--x@  1 neog  staff   2400 Nov 20 16:53 test-app.sh
-rw-------@  1 neog  staff   4036 Nov 17 14:26 ▶-EXECUTAR-AGORA.command
-rw-------@  1 neog  staff   7362 Nov 17 14:13 ⚡-QUICK-START.txt
-rw-r--r--@  1 neog  staff  11744 Nov 21 13:52 🎉-COMPLETION-SUMMARY.md
-rw-------@  1 neog  staff  11349 Nov 17 14:26 🎯-INSTRUCOES-FINAIS.txt
-rw-r--r--@  1 neog  staff   7707 Nov 21 13:45 🎯-START-HERE.md
-rw-------@  1 neog  staff   4693 Nov 21 13:51 📋-QUICK-REFERENCE.md
-rw-r--r--@  1 neog  staff   8476 Nov 21 13:33 📦-DELIVERABLES-INDEX.md
-rw-------@  1 neog  staff  10227 Nov 17 14:23 🔴-LEIA-ISTO.txt
-rw-------@  1 neog  staff   5253 Nov 17 14:10 🚀-START-HERE.md


Now let me read key source files to understand the architecture patterns: